AtObj AtlasObject::LoadFromJSON(JSContext* cx, const std::string& json) { // Convert UTF8 to UTF16 wxString jsonW(json.c_str(), wxConvUTF8); size_t json16len; wxCharBuffer json16 = wxMBConvUTF16().cWC2MB(jsonW.c_str(), jsonW.Length(), &json16len); jsval vp = JSVAL_NULL; JSONParser* parser = JS_BeginJSONParse(cx, &vp); if (!parser) { wxLogError(_T("ParseJSON failed to begin")); return AtObj(); } if (!JS_ConsumeJSONText(cx, parser, reinterpret_cast<const jschar*>(json16.data()), (uint32)(json16len/2))) { wxLogError(_T("ParseJSON failed to consume")); return AtObj(); } if (!JS_FinishJSONParse(cx, parser, JSVAL_NULL)) { wxLogError(_T("ParseJSON failed to finish")); return AtObj(); } AtObj obj; obj.p = ConvertNode(cx, vp); return obj; }
CScriptValRooted ScriptInterface::ParseJSON(const std::string& string_utf8) { std::wstring attrsW = wstring_from_utf8(string_utf8); utf16string string(attrsW.begin(), attrsW.end()); jsval vp; JSONParser* parser = JS_BeginJSONParse(m->m_cx, &vp); if (!parser) { LOGERROR(L"ParseJSON failed to begin"); return CScriptValRooted(); } if (!JS_ConsumeJSONText(m->m_cx, parser, reinterpret_cast<const jschar*>(string.c_str()), (uint32)string.size())) { LOGERROR(L"ParseJSON failed to consume"); return CScriptValRooted(); } if (!JS_FinishJSONParse(m->m_cx, parser, JSVAL_NULL)) { LOGERROR(L"ParseJSON failed to finish"); return CScriptValRooted(); } return CScriptValRooted(m->m_cx, vp); }
NS_IMETHODIMP nsJSONListener::OnStopRequest(nsIRequest *aRequest, nsISupports *aContext, nsresult aStatusCode) { nsresult rv; // This can happen with short UTF-8 messages if (!mSniffBuffer.IsEmpty()) { rv = ProcessBytes(mSniffBuffer.get(), mSniffBuffer.Length()); NS_ENSURE_SUCCESS(rv, rv); } JSBool ok = JS_FinishJSONParse(mCx, mJSONParser, JSVAL_NULL); mJSONParser = nsnull; if (!ok) return NS_ERROR_FAILURE; return NS_OK; }
NS_IMETHODIMP nsJSON::DecodeToJSVal(const nsAString &str, JSContext *cx, jsval *result) { JSAutoRequest ar(cx); JSONParser *parser = JS_BeginJSONParse(cx, result); NS_ENSURE_TRUE(parser, NS_ERROR_UNEXPECTED); JSBool ok = JS_ConsumeJSONText(cx, parser, (jschar*)PromiseFlatString(str).get(), (uint32)str.Length()); // Since we've called JS_BeginJSONParse, we have to call JS_FinishJSONParse, // even if JS_ConsumeJSONText fails. But if either fails, we'll report an // error. ok = ok && JS_FinishJSONParse(cx, parser, JSVAL_NULL); if (!ok) { return NS_ERROR_UNEXPECTED; } return NS_OK; }
void nsJSONListener::Cleanup() { if (mJSONParser) JS_FinishJSONParse(mCx, mJSONParser, JSVAL_NULL); mJSONParser = nsnull; }