1.Json数据格式
1.json是一种轻量级的数据传输格式,表示方法为:“名称”:“值”;(key-value) 2.json通常的格式有两种,对象和数组。 3.对象由花括号括起来的逗号分割的成员构成,对象的成员可以是字符串、数值、数组、对象 对象中包含字符串、数值、对象:
{"name": "张三", "age": 18, "address": {"country" : "china", "province": "广东"}}
4.数组是由方括号括起来的一组值构成,其内容也可以是字符串、数值、对象、数组 数组元素是单纯的字符串:
["张三","李四","王五"]
数组元素是对象
[
{
"name":"张三",
"age":20,
"sex":"男"
},
{
"name":"李四",
"age":18,
"sex":"女"
}
]
二维数组
[
["countru": "中国","province": "四川"],
["countru": "中国","province": "广东"]
]
2.cjson属性
2.1. cjson结构体
cjson源码中使用cJSON结构体存储解析后的json数据,json数据的值可以是字符串、数组、对象、整型、浮点型:
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
cJSON是用双链表写的,通过next / prev指针来查找。只有节点是对象或数组时才可以有孩子节点
typedef struct cJSON {
struct cJSON *next,*prev;
struct cJSON *child;
int type;
char *valuestring;
int valueint;
double valuedouble;
char *string;
} cJSON;
2.2.cjson源码常用函数
cJSON *cJSON_Parse(const char *value);
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
int cJSON_GetArraySize(cJSON *array);
cJSON *cJSON_CreateObject(void);
void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
2.3.示例
解析示例一:
char *json_str = "{\"name\":\"james\",\"sex\":\"boy\",\"age\":20}";
char *str=NULL;
cJSON *cjson_data;
cJSON *cjson_str;
cjson_data = cJSON_Parse(json_str);
if(cjson_data)
{
cjson_str = cJSON_GetObjectItem(cjson_data,"name");
if(cjson_str)printf("%s:%s\r\n",cjson_str->string,cjson_str->valuestring);
cjson_str = cJSON_GetObjectItem(cjson_data,"age");
if(cjson_str)printf("%s:%d\r\n",cjson_str->string,cjson_str->valueint);
cJSON_Delete(cjson_data);
}
解析示例2
json_str = "{ \
\"personA\":{\"name\":\"james\",\"sex\":\"boy\",\"age\":20}, \
\"personB\":{\"name\":\"joe\",\"sex\":\"girl\",\"age\":18} \
}";
int arr_size;
cjson_data = cJSON_Parse(json_str);
if(!cjson_data)
{
printf("json phase error\r\n");
return;
}
printf("%d\r\n",cjson_data->type);
cJSON* personA = cJSON_GetObjectItem(cjson_data,"personA");;
if(personA)
{
str = cJSON_Print(cJSON_GetObjectItem(personA,"name"));
if(str)printf("name:%s\r\n",str);
str = cJSON_Print(cJSON_GetObjectItem(personA,"sex"));
if(str)printf("sex:%s\r\n",str);
str = cJSON_Print(cJSON_GetObjectItem(personA,"age"));
if(str)printf("age:%s\r\n",str);
if(str)free(str);
}
else
{
printf("personA phase error\r\n");
}
```c
创建json数据:
```c
cJSON *root;
cJSON *fmt;
cJSON *img;
cJSON *thm;
int ids[4]={116,943,234,38793};
char *out;
root=cJSON_CreateObject();
cJSON_AddItemToObject(root, "Image", img=cJSON_CreateObject());
cJSON_AddNumberToObject(img,"Width",800);
cJSON_AddNumberToObject(img,"Height",600);
cJSON_AddStringToObject(img,"Title","View from 15th Floor");
cJSON_AddItemToObject(img, "Thumbnail", thm=cJSON_CreateObject());
cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");
cJSON_AddNumberToObject(thm,"Height",125);
cJSON_AddStringToObject(thm,"Width","100");
cJSON_AddItemToObject(img,"IDs", cJSON_CreateIntArray(ids,4));
out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out);
3.使用cjson解析创建
3.1创建、修改和打印
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main()
{
cJSON *root = NULL, *person = NULL;
char *str_print = NULL;
root = cJSON_CreateObject();
person = cJSON_CreateObject();
cJSON_AddItemToObject(root, "person", person);
cJSON_AddStringToObject(person, "firstName", "Lebron");
cJSON_AddStringToObject(person, "lastName", "James");
cJSON_AddNumberToObject(person, "age", 36);
cJSON_AddNumberToObject(person, "height", 206);
cJSON_AddStringToObject(root, "team", "Lakers");
str_print = cJSON_Print(root);
if(str_print != NULL)
{
printf("%s\n", str_print);
cJSON_free(str_print);
str_print = NULL;
}
cJSON_ReplaceItemInObject(person, "firstName", cJSON_CreateString("Chris"));
cJSON_ReplaceItemInObject(person, "lastName", cJSON_CreateString("Paul"));
cJSON_ReplaceItemInObject(person, "age", cJSON_CreateNumber(36));
cJSON_ReplaceItemInObject(person, "height", cJSON_CreateNumber(183));
cJSON_ReplaceItemInObject(root, "team", cJSON_CreateString("sun"));
str_print = cJSON_Print(root);
if(str_print != NULL)
{
printf("\n%s\n", str_print);
cJSON_free(str_print);
str_print = NULL;
}
if(root != NULL)
cJSON_Delete(root);
return 0;
}
执行结果如下:
linux@linux-VirtualBox:~/myfiles/cJson$ gcc app.c cJSON.c -o app
linux@linux-VirtualBox:~/myfiles/cJson$ ./app
{
"person": {
"firstName": "Lebron",
"lastName": "James",
"age": 36,
"height": 206
},
"team": "Lakers"
}
{
"person": {
"firstName": "Chris",
"lastName": "Paul",
"age": 36,
"height": 183
},
"team": "sun"
}
3.2解析JSON格式数据
将上面创建的JSON格式的数据进行解析并输出,解析代码如下。在解析代码中设置的两个数字的类型分别是整数-和小数,在打印时分别以整数和小数进行打印,发现整数打印的结果将小数取整,数值定义的是整数时小数也能打印出从结果,相应的在代码30和31行。 type为cJSON定义的数据的类型,在 cJSON.h 中的88-97行定义
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main()
{
char *cJSON_str = "{ \
\"person\": { \
\"firstName\": \"Lebron\", \
\"lastName\": \"James\", \
\"age\": 36, \
\"height\": 203.5 \
}, \
\"team\": \"Lakers\" \
}";
cJSON *obj = cJSON_Parse(cJSON_str);
cJSON *child = cJSON_GetObjectItem(obj, "person");
cJSON *firstName = cJSON_GetObjectItem(child, "firstName");
cJSON *lastName = cJSON_GetObjectItem(child, "lastName");
cJSON *age = cJSON_GetObjectItem(child, "age");
cJSON *height = cJSON_GetObjectItem(child, "height");
cJSON *team = cJSON_GetObjectItem(obj, "team");
printf("firstName type: 0x%02x, content: %s, %d\n", firstName->type, firstName->valuestring, firstName->valueint);
printf("lastName type: 0x%02x, content: %s, %f\n", lastName->type, lastName->valuestring, lastName->valuedouble);
printf("age type: 0x%02x, content: %d, %f\n", age->type, age->valueint, age->valuedouble);
printf("height type: 0x%02x, content: %d, %f\n", height->type, height->valueint, height->valuedouble);
printf("team type: 0x%02x, content: %s, %d\n", team->type, team->valuestring, team->valueint);
if(obj != NULL)
cJSON_Delete(obj);
return 0;
}
执行结果如下:
linux@linux-VirtualBox:~/myfiles/cJson$ gcc app.c cJSON.c -o app
linux@linux-VirtualBox:~/myfiles/cJson$ ./app
firstName type: 0x10, content: Lebron, 0
lastName type: 0x10, content: James, 0.000000
age type: 0x08, content: 36, 36.000000
height type: 0x08, content: 203, 203.500000
team type: 0x10, content: Lakers, 0
3.3创建和打印JSON数组
#include <stdio.h>
#include "cJSON.h"
typedef struct{
int id;
char *name;
int age;
char *hobby;
}stu_t;
int main(void)
{
int i;
stu_t stu_info[3] = {
{1, "xiaoming", 18, "basketball"},
{2, "xiaolan", 17, "tennis"},
{3, "xiaohong", 18, "piano"}
};
cJSON *root = cJSON_CreateObject();
cJSON *students = cJSON_CreateObject();
cJSON_AddItemToObject(root, "students", students);
cJSON_AddNumberToObject(students, "total", 3);
cJSON *arr_info;
cJSON *stu_arr = cJSON_CreateArray();
cJSON_AddItemToObject(students, "student", stu_arr);
for(i=0; i<sizeof(stu_info)/sizeof(stu_info[0]); ++i)
{
arr_info = cJSON_CreateObject();
cJSON_AddNumberToObject(arr_info, "id", stu_info[i].id);
cJSON_AddStringToObject(arr_info, "name", stu_info[i].name);
cJSON_AddNumberToObject(arr_info, "age", stu_info[i].age);
cJSON_AddStringToObject(arr_info, "hobby", stu_info[i].hobby);
cJSON_AddItemToArray(stu_arr, arr_info);
}
cJSON_AddStringToObject(root, "grade", "senior three");
cJSON *subject = cJSON_CreateArray();
cJSON_AddItemToObject(root, "subject", subject);
cJSON_AddItemToArray(subject, cJSON_CreateString("Chinese"));
cJSON_AddItemToArray(subject, cJSON_CreateString("math"));
cJSON_AddItemToArray(subject, cJSON_CreateString("English"));
char *str_print = cJSON_Print(root);
if(str_print != NULL)
{
printf("%s\n", str_print);
cJSON_free(str_print);
str_print = NULL;
}
if(root != NULL)
cJSON_Delete(root);
return 0;
}
执行结果如下:
linux@linux-VirtualBox:~/myfiles/cJson$ gcc app.c cJSON.c -o app
linux@linux-VirtualBox:~/myfiles/cJson$ ./app
{
"students": {
"total": 3,
"student": [{
"id": 1,
"name": "xiaoming",
"age": 18,
"hobby": "basketball"
}, {
"id": 2,
"name": "xiaolan",
"age": 17,
"hobby": "tennis"
}, {
"id": 3,
"name": "xiaohong",
"age": 18,
"hobby": "piano"
}]
},
"grade": "senior three",
"subject": ["Chinese", "math", "English"]
}
3.4解析JSON数组
将上面创建的JSON格式的数据进行解析并输出,解析代码如下
#include <stdio.h>
#include "cJSON.h"
int main(void)
{
char *str_json = " \
{ \
\"students\" : { \
\"total\" : 3, \
\"student\" : [ \
{ \
\"id\" : 1, \
\"name\" : \"xiaoming\", \
\"age\" : 18, \
\"hobby\" : \"basketball\" \
}, \
{ \
\"id\" : 2, \
\"name\" : \"xiaolan\", \
\"age\" : 17, \
\"hobby\" : \"tennis\" \
}, \
{ \
\"id\" : 3, \
\"name\" : \"xiaohong\", \
\"age\" : 18, \
\"hobby\" : \"piano\" \
} \
] \
}, \
\"grade\" : \"senior three\", \
\"subject\": [\"Chinese\", \"math\", \"English\"] \
} \
";
cJSON *root = cJSON_Parse(str_json);
cJSON *students = cJSON_GetObjectItem(root, "students");
cJSON *total = cJSON_GetObjectItem(students, "total");
cJSON *stu_arr = cJSON_GetObjectItem(students, "student");
int stu_arr_size = cJSON_GetArraySize(stu_arr);
cJSON *grade = cJSON_GetObjectItem(root, "grade");
cJSON *subject_arr = cJSON_GetObjectItem(root, "subject");
int subject_arr_size = cJSON_GetArraySize(subject_arr);
cJSON *item, *id, *name, *age, *hobby, *sub_value;
int i;
printf("total: %d\n", total->valueint);
printf("\nstu_arr_size: %d\n", stu_arr_size);
for(i=0; i<stu_arr_size; ++i)
{
item = cJSON_GetArrayItem(stu_arr, i);
id = cJSON_GetObjectItem(item, "id");
name = cJSON_GetObjectItem(item, "name");
age = cJSON_GetObjectItem(item, "age");
hobby = cJSON_GetObjectItem(item, "hobby");
printf("id:%-1d, name:%-8s, age:%-2d, hobby:%-10s\n", id->valueint, name->valuestring, age->valueint, hobby->valuestring);
}
printf("\ngrade: %s\n", grade->valuestring);
printf("\nsubject_arr_size: %d\n", subject_arr_size);
printf("subject is: ");
for(i=0; i<subject_arr_size; ++i)
{
sub_value = cJSON_GetArrayItem(subject_arr, i);
printf("%s ", sub_value->valuestring);
}
printf("\n");
if(root != NULL)
{
cJSON_Delete(root);
root = NULL;
students = NULL;
total = NULL;
stu_arr = NULL;
grade = NULL;
}
return 0;
}
执行结果如下
linux@linux-VirtualBox:~/myfiles/cJson$ gcc app.c cJSON.c -o app
linux@linux-VirtualBox:~/myfiles/cJson$ ./app
total: 3
stu_arr_size: 3
id:1, name:xiaoming, age:18, hobby:basketball
id:2, name:xiaolan , age:17, hobby:tennis
id:3, name:xiaohong, age:18, hobby:piano
grade: senior three
subject_arr_size: 3
subject is: Chinese math English
4.从文件解析/生成
4.1从json文件解析
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include<sys/stat.h>
#include "cJSON.h"
#define FILENAME "./test.json"
typedef struct
{
int id;
char firstName[32];
char lastName[32];
char email[64];
int age;
float height;
}people;
int cJSON_to_struct_array(char *text, people worker[])
{
cJSON *json,*arrayItem,*item,*object;
int i = 0;
json=cJSON_Parse(text);
if (!json)
{
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
}
else
{
arrayItem=cJSON_GetObjectItem(json,"people");
if(arrayItem!=NULL)
{
int size=cJSON_GetArraySize(arrayItem);
printf("cJSON_GetArraySize: size=%d\n",size);
for(i=0;i<size;i++)
{
printf("i=%d\n",i);
object=cJSON_GetArrayItem(arrayItem,i);
item=cJSON_GetObjectItem(object,"firstName");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s\n",item->type,item->string);
memcpy(worker[i].firstName,item->valuestring,strlen(item->valuestring));
}
item=cJSON_GetObjectItem(object,"lastName");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n",item->type,item->string,item->valuestring);
memcpy(worker[i].lastName,item->valuestring,strlen(item->valuestring));
}
item=cJSON_GetObjectItem(object,"email");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n",item->type,item->string,item->valuestring);
memcpy(worker[i].email,item->valuestring,strlen(item->valuestring));
}
item=cJSON_GetObjectItem(object,"age");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valueint=%d\n",item->type,item->string,item->valueint);
worker[i].age=item->valueint;
}
else
{
printf("cJSON_GetObjectItem: get age failed\n");
}
item=cJSON_GetObjectItem(object,"height");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, value=%f\n",item->type,item->string,item->valuedouble);
worker[i].height=item->valuedouble;
}
}
}
printf("\n\n");
for(i=0;i<3;i++)
{
printf("i=%d, firstName=%s,lastName=%s,email=%s,age=%d,height=%f\n",
i,
worker[i].firstName,
worker[i].lastName,
worker[i].email,
worker[i].age,
worker[i].height);
}
cJSON_Delete(json);
}
return 0;
}
size_t get_file_size(const char *filepath)
{
if(NULL == filepath)
return 0;
struct stat filestat;
memset(&filestat,0,sizeof(struct stat));
if(0 == stat(filepath,&filestat))
return filestat.st_size;
else
return 0;
}
void read_file(char *filename)
{
FILE *fp;
people worker[3]={{0}};
size_t size = get_file_size(filename);
if(0 == size)
{
printf("get_file_size failed!!!\n");
}
char *buf = malloc(size+1);
if(NULL == buf)
{
printf("malloc failed!!!\n");
}
memset(buf,0,size+1);
fp=fopen(filename,"rb");
fread(buf,1,size,fp);
fclose(fp);
printf("read file %s complete, size=%d.\n",filename,size);
cJSON_to_struct_array(buf, worker);
free(buf);
}
int main(int argc, char **argv)
{
read_file(FILENAME);
return 0;
}
4.2生成json文件
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include "cJSON.h"
int main(int argc, char *argv[])
{
cJSON* cjson_test = NULL;
cJSON* cjson_name = NULL;
cJSON* cjson_age = NULL;
cJSON* cjson_weight = NULL;
cJSON* cjson_address = NULL;
cJSON* cjson_address_country = NULL;
cJSON* cjson_address_zipcode = NULL;
cJSON* cjson_skill = NULL;
char* str = NULL;
cjson_test = cJSON_CreateObject();
cJSON_AddStringToObject(cjson_test, "name", "mculover666");
cJSON_AddNumberToObject(cjson_test, "age", 22);
cJSON_AddNumberToObject(cjson_test, "weight", 55.5);
cjson_name = cJSON_GetObjectItem(cjson_test, "name");
cjson_age = cJSON_GetObjectItem(cjson_test, "age");
cjson_weight = cJSON_GetObjectItem(cjson_test, "weight");
printf("name: %s\n", cjson_name->valuestring);
printf("age:%d\n", cjson_age->valueint);
printf("weight:%.1f\n", cjson_weight->valuedouble);
cjson_address = cJSON_CreateObject();
cJSON_AddStringToObject(cjson_address, "country", "China");
cJSON_AddNumberToObject(cjson_address, "zip-code", 111111);
cJSON_AddItemToObject(cjson_test, "address", cjson_address);
cjson_address = cJSON_GetObjectItem(cjson_test, "address");
cjson_address_country = cJSON_GetObjectItem(cjson_address, "country");
cjson_address_zipcode = cJSON_GetObjectItem(cjson_address, "zip-code");
printf("address-country:%s\naddress-zipcode:%d\n", cjson_address_country->valuestring, cjson_address_zipcode->valueint);
cjson_skill = cJSON_CreateArray();
cJSON_AddItemToArray(cjson_skill, cJSON_CreateString( "C" ));
cJSON_AddItemToArray(cjson_skill, cJSON_CreateString( "Java" ));
cJSON_AddItemToArray(cjson_skill, cJSON_CreateString( "Python" ));
cJSON_AddItemToObject(cjson_test, "skill", cjson_skill);
cJSON_AddFalseToObject(cjson_test, "student");
str = cJSON_Print(cjson_test);
printf("%s\n", str);
FILE* fp = fopen("text.json","w+");
printf("....\n");
fwrite(str,sizeof(char),strlen(str)+1,fp);
fclose(fp);
return 0;
}
生成的结果内容如下
{
"name": "mculover666",
"age": 22,
"weight": 55.500000,
"address": {
"country": "China",
"zip-code": 111111
},
"skill": ["C", "Java", "Python"],
"student": false
}
int main(int argc, char *argv[])
{
cJSON* obj = cJSON_CreateObject();
cJSON* subObj = cJSON_CreateObject();
cJSON_AddItemToObject(subObj,"factory",cJSON_CreateString("一汽大众"));
cJSON_AddItemToObject(subObj,"last",cJSON_CreateNumber(31));
cJSON_AddItemToObject(subObj,"price",cJSON_CreateNumber(83));
cJSON_AddItemToObject(subObj,"sell",cJSON_CreateNumber(49));
cJSON_AddItemToObject(subObj,"sum",cJSON_CreateNumber(80));
cJSON* array = cJSON_CreateArray();
cJSON_AddItemToArray(array,cJSON_CreateNumber(123));
cJSON_AddItemToArray(array,cJSON_CreateNumber(1));
cJSON_AddItemToArray(array,cJSON_CreateString("hello,world"));
cJSON* childObj = cJSON_CreateObject();
cJSON_AddItemToObject(childObj,"梅塞奔驰",cJSON_CreateString("心所向,持以恒"));
cJSON_AddItemToArray(array,childObj);
cJSON_AddItemToObject(subObj,"othre",array);
cJSON_AddItemToObject(obj,"奔驰",subObj);
char* data = cJSON_Print(obj);
FILE* fp = fopen("car.json","w");
fwrite(data,sizeof(char),strlen(data)+1,fp);
fclose(fp);
cJSON_Delete(obj );
free(data );
return 0;
}
{
"奔驰": {
"factory": "一汽大众",
"last": 31,
"price": 83,
"sell": 49,
"sum": 80,
"othre": [123, 1, "hello,world", {
"梅塞奔驰": "心所向,持以恒"
}]
}
}
补充
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include "cJSON.h"
typedef struct
{
int id;
char firstName[32];
char lastName[32];
char email[64];
int age;
float height;
}people;
void dofile(char *filename);
int main(int argc, char **argv)
{
dofile("json_str3.txt");
return 0;
}
int cJSON_to_str(char *json_string, char *str_val)
{
cJSON *root=cJSON_Parse(json_string);
if (!root)
{
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
return -1;
}
else
{
cJSON *item=cJSON_GetObjectItem(root,"firstName");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, key is %s, value is %s\n",item->type,item->string,item->valuestring);
memcpy(str_val,item->valuestring,strlen(item->valuestring));
}
cJSON_Delete(root);
}
return 0;
}
int cJSON_to_struct(char *json_string, people *person)
{
cJSON *item;
cJSON *root=cJSON_Parse(json_string);
if (!root)
{
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
return -1;
}
else
{
cJSON *object=cJSON_GetObjectItem(root,"person");
if(object==NULL)
{
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
cJSON_Delete(root);
return -1;
}
printf("cJSON_GetObjectItem: type=%d, key is %s, value is %s\n",object->type,object->string,object->valuestring);
if(object!=NULL)
{
item=cJSON_GetObjectItem(object,"firstName");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n",item->type,item->string,item->valuestring);
memcpy(person->firstName,item->valuestring,strlen(item->valuestring));
}
item=cJSON_GetObjectItem(object,"lastName");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n",item->type,item->string,item->valuestring);
memcpy(person->lastName,item->valuestring,strlen(item->valuestring));
}
item=cJSON_GetObjectItem(object,"email");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n",item->type,item->string,item->valuestring);
memcpy(person->email,item->valuestring,strlen(item->valuestring));
}
item=cJSON_GetObjectItem(object,"age");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valueint=%d\n",item->type,item->string,item->valueint);
person->age=item->valueint;
}
else
{
printf("cJSON_GetObjectItem: get age failed\n");
}
item=cJSON_GetObjectItem(object,"height");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valuedouble=%f\n",item->type,item->string,item->valuedouble);
person->height=item->valuedouble;
}
}
cJSON_Delete(root);
}
return 0;
}
int cJSON_to_struct_array(char *text, people worker[])
{
cJSON *json,*arrayItem,*item,*object;
int i;
json=cJSON_Parse(text);
if (!json)
{
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
}
else
{
arrayItem=cJSON_GetObjectItem(json,"people");
if(arrayItem!=NULL)
{
int size=cJSON_GetArraySize(arrayItem);
printf("cJSON_GetArraySize: size=%d\n",size);
for(i=0;i<size;i++)
{
printf("i=%d\n",i);
object=cJSON_GetArrayItem(arrayItem,i);
item=cJSON_GetObjectItem(object,"firstName");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s\n",item->type,item->string);
memcpy(worker[i].firstName,item->valuestring,strlen(item->valuestring));
}
item=cJSON_GetObjectItem(object,"lastName");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n",item->type,item->string,item->valuestring);
memcpy(worker[i].lastName,item->valuestring,strlen(item->valuestring));
}
item=cJSON_GetObjectItem(object,"email");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n",item->type,item->string,item->valuestring);
memcpy(worker[i].email,item->valuestring,strlen(item->valuestring));
}
item=cJSON_GetObjectItem(object,"age");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, valueint=%d\n",item->type,item->string,item->valueint);
worker[i].age=item->valueint;
}
else
{
printf("cJSON_GetObjectItem: get age failed\n");
}
item=cJSON_GetObjectItem(object,"height");
if(item!=NULL)
{
printf("cJSON_GetObjectItem: type=%d, string is %s, value=%f\n",item->type,item->string,item->valuedouble);
worker[i].height=item->valuedouble;
}
}
}
for(i=0;i<3;i++)
{
printf("i=%d, firstName=%s,lastName=%s,email=%s,age=%d,height=%f\n",
i,
worker[i].firstName,
worker[i].lastName,
worker[i].email,
worker[i].age,
worker[i].height);
}
cJSON_Delete(json);
}
return 0;
}
void dofile(char *filename)
{
FILE *f;
int len;
char *data;
f=fopen(filename,"rb");
fseek(f,0,SEEK_END);
len=ftell(f);
fseek(f,0,SEEK_SET);
data=(char*)malloc(len+1);
fread(data,1,len,f);
fclose(f);
printf("read file %s complete, len=%d.\n",filename,len);
people worker[3]={{0}};
cJSON_to_struct_array(data, worker);
free(data);
}
|