cJSON 解析JSON实例

前端之家收集整理的这篇文章主要介绍了cJSON 解析JSON实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

cJSON 解析的数据

The result of GET http://127.0.0.1:9871/iPhone_settings/mobile_devices/paired_devices

{
    "STATUS": {"RESULT": "SUCCESS","DETAIL": "Success"},"ITEMS":
    [ { "HASHVAL": 769973531,"CNAME": "paired_devices","TYPE": "T_LIST_PAIRED_DEVICES_V1","NAME": "VALUE": [ {"DEVICE ID": "d1b9b0aa63c80427","DEVICE NAME": "VIZIO XR6P10"},{"DEVICE ID": "12345","DEVICE NAME": "JS_POSTMAN_1"},{"DEVICE ID": "fff3149104611fff","DEVICE NAME": "SIGMA_VIZIO_UI"} ] } ],"HASHLIST": [722496676,606446411],"URI": "/menu_native/dynamic/tv_settings/mobile_devices/paired_devices","PARAMETERS": {"FLAT": "SYS_NOERROR","HELPTEXT": "SYS_Failed","HASHONLY": "SYS_Failed"} }

code example

int i = 0;
cJSON* item_json = NULL;
cJSON* array_json = NULL;
cJSON* elem_json = NULL;
cJSON* signleArrElem_json = NULL;

item_json = cJSON_GetObjectItem(root_json,"ITEMS");
if (item_json == NULL) {
    MICRO_ERROR("No ITEMS string found: %s\n",cJSON_GetErrorPtr());
    ret = BE_Failed;
    goto EXIT;
}

signleArrElem_json = cJSON_GetArrayItem(item_json,0);
if (signleArrElem_json == NULL) {
    MICRO_ERROR("cJSON_GetArrayItem() Failed,: %s. \n",cJSON_GetErrorPtr());
    ret = BE_Failed;
    goto EXIT;
}
array_json = cJSON_GetObjectItem(signleArrElem_json,"VALUE");
if (array_json == NULL) {
    MICRO_ERROR("No VALUE string found: %s\n",cJSON_GetErrorPtr());
    ret = BE_Failed;
    goto EXIT;
}

for (i = 0; i < cJSON_GetArraySize(array_json); ++i) {
    item_json = cJSON_GetArrayItem(array_json,i);
    if (array_json == NULL) continue;

    elem_json = cJSON_GetObjectItem(item_json,"DEVICE NAME");
    if (elem_json == NULL) {
        MICRO_ERROR("cJSON_GetObjectItem() Failed,cJSON_GetErrorPtr());
        ret = BE_Failed;
        goto EXIT;
    }
    memcpy(myDevicesList[i].deviceName,elem_json->valuestring,strlen(elem_json->valuestring));
    MICRO_ERROR("myDevicesList[i].deviceName: %s\n",myDevicesList[i].deviceName);

    elem_json = cJSON_GetObjectItem(item_json,"DEVICE ID");
    if (elem_json == NULL) {
        MICRO_ERROR("cJSON_GetObjectItem() Failed,cJSON_GetErrorPtr());
        ret = BE_Failed;
        goto EXIT;
    }
    .......
    MICRO_ERROR("myDevicesList[i].deviceId: %s\n",myDevicesList[i].deviceId);

}
.....
EXIT:
    cJSON_Delete(root_json);

    return ret;
原文链接:https://www.f2er.com/json/289126.html

猜你在找的Json相关文章