一、c语言获取json中的数据。
@H_502_15@1、先要有cJOSN库,两个文件分别是cJSON.c和cJSON.h。
二、cJSON库
@H_502_15@1、json的数据结构
@H_502_15@c语言中json数据是采用链表存储的
@H_502_15@
typedef struct cJSON {
@H_502_15@
struct cJSON *next,*prev;// 数组 对象数据中用到
@H_502_15@
struct cJSON *child;// 数组 和对象中指向子数组对象或值
@H_502_15@
int type;// 元素的类型,如是对象还是数组
@H_502_15@
char *valuestring;// 如果是字符串
@H_502_15@
int valueint;// 如果是数值
@H_502_15@
double valuedouble;// 如果类型是cJSON_Number
@H_502_15@
char *string;// The item's name string,if this item is the child of,or is in the list of subitems of an object.
@H_502_15@
} cJSON;
三、cJSON使用
@H_502_15@
{
@H_502_15@
"name": "Jack (\"Bee\") Nimble",
@H_502_15@
"format": {
@H_502_15@
"type": "rect",
@H_502_15@
"width": 1920,
@H_502_15@
"height": 1080,
@H_502_15@
"interlace": false,
@H_502_15@
"frame rate": 24
@H_502_15@
}
@H_502_15@
}
@H_502_15@
"name": "Jack (\"Bee\") Nimble",
@H_502_15@
"format": {
@H_502_15@
"type": "rect",
@H_502_15@
"width": 1920,
@H_502_15@
"height": 1080,
@H_502_15@
"interlace": false,
@H_502_15@
"frame rate": 24
@H_502_15@
}
@H_502_15@
}
@H_502_15@
1、字符串解析成json结构体
@H_502_15@
1):讲字符串解析成json结构体。
@H_502_15@
cJSON *root = cJSON_Parse(my_json_string);
@H_502_15@
2):获取某个元素
@H_502_15@
cJSON *format = cJSON_GetObjectItem(root,"format");
@H_502_15@
int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
@H_502_15@
int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
@H_502_15@
3):讲json结构体转换成字符串
@H_502_15@
char *rendered=cJSON_Print(root);
@H_502_15@
4):删除
@H_502_15@
cJSON_Delete(root);
@H_502_15@
2:构建一个json结构体
@H_502_15@
cJSON *root,*fmt;
@H_502_15@
root=cJSON_CreateObject();
@H_502_15@
cJSON_AddItemToObject(root,"name",cJSON_CreateString("Jack (\"Bee\") Nimble"));
@H_502_15@
cJSON_AddItemToObject(root,"format",fmt=cJSON_CreateObject());
@H_502_15@
cJSON_AddStringToObject(fmt,"type","rect");
@H_502_15@
cJSON_AddNumberToObject(fmt,"width",1920);
@H_502_15@
cJSON_AddNumberToObject(fmt,"height",1080);
@H_502_15@
cJSON_AddFalseToObject (fmt,"interlace");
@H_502_15@
cJSON_AddNumberToObject(fmt,"frame rate",24)
@H_502_15@out =cJSON_Print(root);
@H_502_15@printf("%s\n",out);
@H_502_15@cJSON_Delete(root);
@H_502_15@free(out);