cJSON笔记
github地址: https://github.com/DaveGamble/cJSON
需要将cJSON.h 和 cJSON.c拷贝到路径下,并且连接所需库文件 -lm
步骤:
1、先将普通的json串处理成json对象,也就是所谓的创建json root的过程
char *js_string;
cJSON *root;
root = cJSON_Parse(js_string);
注意:
解析完成后,需释放
if(root)
cJSON_Delete(root);
2、开始拿关键字,但如果关键字还有父层或者祖层,那就需要先从父层开拿,所谓剥洋葱是也!
先说没有父层的:
{"name": "xiaohong", "age": 10}
可以这样搞:
char *s = "{\"name\":\"xiao hong\",\"age\":10}";
cJSON *root = cJSON_Parse(s);
cJSON *name = cJSON_GetObjectItem(root, "name");
printf("name type is %d\n", name->type);
printf("name is %s\n", name->valuestring);
cJSON *age = cJSON_GetObjectItem(root, "age");
printf("age type is %d\n", age->type);
printf("age is %d\n", age->valueint);
再说有父层的:
{"list":{"name":"xiao hong",
"age":10},
"other":{"name":"hua hua"}}
char *s = "{\"list\":{\"name\":\"xiao hong\",\"age\":10},\"other\":{\"name\":\"hua hua\"}}";
cJSON *root = cJSON_Parse(s);
cJSON *js_list=cJSON_GetObjectItem(root, "list");
printf("list type is %d\n",js_list->type);
cJSON *name = cJSON_GetObjectItem(js_list, "name");
printf("name type is %d\n",name->type);
printf("name is %s\n",name->valuestring);
cJSON *age = cJSON_GetObjectItem(js_list, "age");
printf("age type is %d\n", age->type);
printf("age is %d\n",age->valueint);
cJSON *js_other = cJSON_GetObjectItem(root, "other");
printf("list type is %d\n",js_other->type);
cJSON *js_name = cJSON_GetObjectItem(js_other, "name");
printf("name type is %d\n",js_name->type);
printf("name is %s\n",js_name->valuestring);
if(root)
cJSON_Delete(root);
return 0;
3、数组
char *s = "{\"list\":[\"name1\",\"name2\"]}";
cJSON *root = cJSON_Parse(s);
cJSON *js_list = cJSON_GetObjectItem(root, "list");
int array_size = cJSON_GetArraySize(js_list);
int i = 0;
cJSON *item;
for(i=0; i< array_size; i++) {
item = cJSON_GetArrayItem(js_list, i);
printf("item type is %d\n",item->type);
printf("%s\n",item->valuestring);
}
---------------------------------------------
常用API(在文件cJSON.h中)
--解析json
1、从给定的json字符串中得到cjson对象
extern cJSON *cJSON_Parse(const char *value);
2、从json对象中获取有格式的json对象
extern char *cJSON_Print(cJSON *item);
3、从cjson中获取无格式的json对象
extern char *cJSON_PrintUnformatted(cJSON *item);
4、删除cjson对象,释放链表所占用的内存空间
extern void cJSON_Delete(cJSON *c);
5、获取cjson对象数组成员的个数
extern int cJSON_GetArraySize(cJSON *array);
6、根据下标获取cjson对象数组中的对象
extern cJSON_GetArrayItem(cJSON *array, int item);
7、根据键获取对应的值(cjson对象)
extern cJSON *cJSON_GetObjectItem(cJSON *object, const char *string);
8、获取错误字符串
extern const char *cJSON_GetErrorPtr(void);
--构造json
extern cJSON *cJSON_CreateObject(void);
extern void cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreatTrue(void);
extern cJSON *cJSON_createFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);