admin';?>

首页 / Development & communication

c++ parse json

By admin •  2018-10-28 15:21:51 •  110次点击
By HTML5, We can do with json easilly.
var oJson = { 'ip': oIp.value, 'port': oPort.value };

//json object => json string
var strJson = JSON.stringify(oJson );

//json string => json obj
var oJson2 = JSON.parse(strJson, function(k, v){
   //v = v*2; //you can modify data, before it be returned.
   console.log(k);
});

when strJson be passed into c++, then How We to do with it?
the answer  is  following:
    conat char* buffer="your json data";
    do{
        nsCOMPtr<nsIWebBrowser> webBrowser=pWrapper->GetWebBrowser();
        if(!webBrowser) break;

        nsCOMPtr<nsIDocShell>  docShell;
        docShell = CMozUtil::GetDocShell(webBrowser);
        if(!docShell) break;
        nsCOMPtr<nsIScriptGlobalObject> global(do_GetInterface(docShell)); 

        bool bOK = false;
        mozilla::dom::AutoJSAPI jsapi;
        jsapi.Init();
        JSContext* cx = jsapi.cx(); 
        if (!cx) break;

        // Now parse the JSON so that we resolve with a JS Object.
        JS::Rooted<JSObject*> globalJSObject(cx, global->GetGlobalJSObject());
        JSAutoNullableCompartment ac(cx, globalJSObject);
        JS::Rooted<JS::Value> json(cx);

        nsString aOutput;
        //UTF8 ---> UTF16
        NS_CStringToUTF16(nsCString(buffer), NS_CSTRING_ENCODING_UTF8, aOutput);

        if (!JS_ParseJSON(cx, aOutput.get(), aOutput.Length(), &json))
        {
            printf("JS_ParseJSON error!n");
            break;
        } 
        if (!json.isObject()) break;
        JSObject* pJsonObj = &json.toObject(); 
        JS::Rooted<JSObject*> jRootObj(cx,pJsonObj); 

        JS::Rooted<JS::Value> jsIp(cx);
        JS::Rooted<JS::Value> jsPort(cx);
        bOK = JS_GetProperty(cx, jRootObj, "ip",   &jsIp);
        bOK = JS_GetProperty(cx, jRootObj, "port", &jsPort);
        char* chIp   = JS_EncodeString(cx, jsIp.toString());
        char* chPort = JS_EncodeString(cx, jsPort.toString());
        PRUint16 wdPort = atoi(chPort);
        g_print ("ip: %s, port: %s n", chIp, chPort);
    }while(0);



Reference:
[1] https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON

0 回复 | 直到2019-06-26 15:25添加回复

回复

登录发表 or 还没有账号?去注册

他山跨平台混合应用开发框架

现在注册 已注册请 登入
Development & communication

节点列表