{
    "code":"aaaaa",
    "cmd":1,
    "data":[
        {
            "ip":"192.168.0.1",
            "port":8
        },
        {
            "ip":"192.168.0.2",
            "port":89
        }
    ]
}

解析上面的json串

	char data[256] = "{\"code\":\"aaaaa\",\"cmd\":1,\"data\":[{\"ip\":\"192.168.0.1\",\"port\":8},{\"ip\":\"192.168.0.1\",\"port\":89}]}";
    cJSON *json=cJSON_Parse(data);
    cJSON *item = cJSON_GetObjectItem(json,"code");
    printf("scode : %s\n",item->valuestring);
    item = cJSON_GetObjectItem(json,"cmd");
    printf("cmd   : %d\n",item->valueint);
    cJSON *d_list = cJSON_GetObjectItem(json,"data");
    int arr_size = cJSON_GetArraySize(d_list);
    cJSON* arr_item_list = d_list->child;

    int i = 0;
    int j = 0;
    for(i=0;i <=(arr_size-1);++i){
        cJSON *send_list = cJSON_GetObjectItem(arr_item_list,"ip");
        printf("ip : %s\n",send_list->valuestring);
        send_list = cJSON_GetObjectItem(arr_item_list,"port");
        printf("port   : %d\n",send_list->valueint);
        arr_item_list = arr_item_list->next;
    }
    cJSON_Delete(json);
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐