C语言解析json字符串

C语言解析json格式字符串下载cJSON库并导入cJSON.c和cJSON.h 文件,最后把自己的写的.c文件和cJSON.c一起编译,如:gcc -g json.c cJSON.c -o json.exe 前面json.c是我自己编写的c文件,后者cJSON.c是cJSON库中的。
cJSON库下载:https://sourceforge.net/projects/cjson/

#include 
#include "cJSON.h"
int main() {
    cJSON           *json;
    char              *out;
             json=cJSON_Parse("{\"requestId\": \"ff36a3cc-ec34-11e6-b1a0-64510650abcf\",\"inputs\": [{\"intent\": \"action.devices.SYNC\"}]}");
            out=cJSON_Print(json);  //这个是可以输出的。为获取的整个json的值
            printf("%s\n",out);
            cJSON *item = cJSON_GetObjectItem(json,"requestId");  //
            printf("requestId:%s\n",item->valuestring);
            cJSON *arrayItem = cJSON_GetObjectItem(json,"inputs"); //获取这个对象成员
            cJSON *object = cJSON_GetArrayItem(arrayItem,0);   //因为这个对象是个数组获取,且只有一个元素所以写下标为0获取
            /*下面就是可以重复使用cJSON_GetObjectItem来获取每个成员的值了*/
             cJSON *item1 = cJSON_GetObjectItem(object,"intent");  //
            printf("intent:%s\n",item1->valuestring);
            cJSON_Delete(json);
            fclose(fp);
}

执行结果:

{
        "requestId":    "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
        "inputs":       [{
                        "intent":       "action.devices.SYNC"
                }]
}
requestId:ff36a3cc-ec34-11e6-b1a0-64510650abcf
inputs.intent:action.devices.SYNC

你可能感兴趣的:(c,json)