parson json解析

最近交互数据中用到JSON数据,很多年以前用过CJSON解析和生成JSON数据,貌似CJSON已经发展成为了libjson,本打算用libjson库,不过其提供的解析JSON方式采用了回调,是测试过程中总是出错,无赖放弃。parson(http://www.oschina.net/p/parson)基于点分K/V形式来设置和获取值,非常方便使用,官方提供了大量的测试程序。parson的使用也非常方便,一个头文件,一个c文件,引用编译即可。

下面是一个使用parson解析JSON数据的例子,主要测试复杂的json结构。

{"desString":"P7svG%2BLoUZEbB8Le5jP1%2BpuX2OVWLE4xWMzFcYFCRvNvDlcFVm%2B8z2VFO%2F%2BaEB8UAMa%2FZ0GGhooGNMWFE98Zmw%3D%3D","caller":{"mobile":"13996130361"},"accountId":"b5091dc91d700c6bf714e5fc446797d3","tmpTime":1428545890,"otherParam":"{id:12}","participant":[{"mobile":"18623582801"}],"servletUrl":"http://192.168.1.1:8090/xdr"}

    JSON_Value *root_value=NULL;
    root_value = json_parse_string(jsonstr);
    JSON_Object *root_object;
    if(json_value_get_type(root_value) == JSONObject)
    {
        root_object = json_value_get_object(root_value);
        const char *desString = json_object_get_string(root_object, "desString");
        if(desString!=NULL)strncpy(pPost->desString,desString,LENGTH128-1);
        const char *accountId = json_object_get_string(root_object, "accountId");
        if(accountId!=NULL)strncpy(pPost->accountId,accountId,LENGTH32);
        double tmpTime = json_object_get_number(root_object, "tmpTime");
        const char *caller = json_object_dotget_string(root_object,"caller.mobile");
        if(caller!=NULL)strncpy(pPost->caller,caller,LENGTH16-1);
        const char *servletUrl = json_object_dotget_string(root_object,"servletUrl");
        if(servletUrl!=NULL)strncpy(pPost->servletUrl,servletUrl,LENGTH128-1);
        const char *otherParam = json_object_dotget_string(root_object,"otherParam");
        if(otherParam!=NULL)strncpy(pPost->otherParam,otherParam,LENGTH128-1);

        JSON_Array *array;
        array = json_object_get_array(root_object, "participant");
        int i =0;
        for(i;i<json_array_get_count(array);i++)
        {
            JSON_Object *tmp = json_array_get_object(array,i);
            if(tmp!=NULL)
            {
                const char *mobile = json_object_get_string(tmp,"mobile");
                if(mobile!=NULL)strncpy(pPost->callee,mobile,LENGTH16-1);
            }
        }
    }
    if(root_value)json_value_free(root_value);

posted on 2017-12-21 10:43  angry-baby  阅读(1147)  评论(0编辑  收藏  举报

导航