extern cJSON *cJSON_Parse(const char *value);
(PS:把一个字符串数组转换成 JSON数据对象, 每次解析数据之前,必须要看当前的数据是否能转换成JSON数据格式。)
参数一:需要转换的字符串
返回值:转换成功:返回JSON对象 转换失败:返回NULL
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
参数一:需要获取的对象 (转换后的cJSON对象)
参数二:对应的key值
返回值:成功:返回key对应的value 失败:返回NULL
extern char *cJSON_Print(cJSON *item);
extern int cJSON_GetArraySize(cJSON *array);返回值:该对象成员的个数
cJSON *cJSON_GetArrayItem(cJSON *array,int item); 返回值:成功:JSON对象失败:返回NULL
extern char *cJSON_Print(cJSON *item);
extern char *cJSON_PrintUnformatted(cJSON *item);
extern void cJSON_Delete(cJSON *c);
extern int cJSON_GetArraySize(cJSON *array);
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
extern const char *cJSON_GetErrorPtr(void);
{"display": {"deviceList": [{"hostID": 10000,"name": "a"}, {"hostID": 10001,"name": "b"}]},"version": "1.0"
}
#include
#include "cJSON.h"
#include
#include
#include
#include int main()
{cJSON *hostID_item = NULL;cJSON *nameItem = NULL;cJSON *deviceListArray = cJSON_CreateArray();cJSON_AddItemToArray(deviceListArray,hostID_item=cJSON_CreateObject());cJSON_AddItemToObject(hostID_item, "hostID", cJSON_CreateNumber(10000));cJSON_AddItemToArray(deviceListArray,hostID_item=cJSON_CreateObject());cJSON_AddItemToObject(hostID_item, "name", cJSON_CreateString("a"));cJSON_AddItemToArray(deviceListArray,hostID_item=cJSON_CreateObject());cJSON_AddItemToObject(hostID_item, "hostID", cJSON_CreateNumber(10001));cJSON_AddItemToArray(deviceListArray,hostID_item=cJSON_CreateObject());cJSON_AddItemToObject(hostID_item, "name", cJSON_CreateString("b"));cJSON *deviceList = cJSON_CreateObject();cJSON_AddItemToObject(deviceList, "deviceList", deviceListArray);cJSON *root = cJSON_CreateObject();cJSON_AddItemToObject(root, "display", deviceList);cJSON_AddItemToObject(root,"version",cJSON_CreateString("1.0"));printf("%s\n", cJSON_Print(root)); return 0;
}
#include
#include "cJSON.h"
#include
#include
#include
#include char *data = "{\"display\":{\"deviceList\":[{\"hostID\":10000,\"name\":\"a\"},{\"hostID\":10001,\"name\":\"b\"}]},\"version\":\"1.0\"}";
int main()
{cJSON *root = cJSON_Parse(data);if(root == NULL){printf("get root fail!!!\n");return -1;}else{cJSON *value = cJSON_GetObjectItem(root,"version");if(value == NULL){printf("get value fail!!!\n");return -1;}printf("version = %s\n", value->valuestring);value = cJSON_GetObjectItem(root,"display");if(value != NULL){value = cJSON_GetObjectItem(value,"deviceList");if(value != NULL){int size = cJSON_GetArraySize(value);for(int i=0; i<size; i++){cJSON *array = cJSON_GetArrayItem(value, i);if(array != NULL){cJSON *item = cJSON_GetObjectItem(array,"name");if(item != NULL){printf("name = %s\n", item->valuestring);}item = cJSON_GetObjectItem(array,"hostID");if(item != NULL){printf("hostID = %d\n", item->valueint);}}}}}}return 0;
}

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!