IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> C++知识库 -> cJSON库的使用 -> 正文阅读

[C++知识库]cJSON库的使用

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 //json的值为整型或者浮点型
#define cJSON_String 4 //json的值为字符串
#define cJSON_Array 5 //json的值为数组
#define cJSON_Object 6 //json的值为对象

cJSON是用双链表写的,通过next / prev指针来查找。只有节点是对象或数组时才可以有孩子节点
/* 遍历数组或对象链的前向或后向链表指针*/
/*数组或对象的孩子节点*/
/* 键的类型*/
/*字符串值*/
/* 整数值*/
/* 浮点数值*/
/* 键的名字*/
typedef struct cJSON {
	struct cJSON *next,*prev;	/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
	struct cJSON *child;		/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */

	int type;					/* The type of the item, as above. */

	char *valuestring;			/* The item's string, if type==cJSON_String */
	int valueint;				/* The item's number, if type==cJSON_Number */
	double valuedouble;			/* The item's number, if type==cJSON_Number */

	char *string;				/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;

2.2.cjson源码常用函数

/*
函数功能:将json格式的字符串转换成cJSON结构体
说明:这个函数会调用malloc动态分配内存,使用后必须调用cJSON_Delete函数释放内存。
*/
cJSON *cJSON_Parse(const char *value);

/*
函数功能:根据传入的名称,查找cJSON对象中对应的值
函数参数:object使用cJSON_Parse解析得到的cJSON结构体 string表示json对象的名称字符串
返回值:返回存储json名称、值、类型等数内容的结构体
*/
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);

/*
函数功能:获取json数组的元素个数
*/
int	  cJSON_GetArraySize(cJSON *array);

/*
函数功能:初始化cJSON链表,分配内存空间
*/
cJSON *cJSON_CreateObject(void);

/*
函数功能:向json的object中添加对象元素
函数参数:object表示需要添加cJSON指针,string表示需要添加对象的名称,item表示需要添加对象的值
*/
void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);

/* 向json数据中添加内容*/
#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);//将json字符串转化成CJSON结构体类型的数据
if(cjson_data)
{
	cjson_str = cJSON_GetObjectItem(cjson_data,"name");//获取名称为name的值
	if(cjson_str)printf("%s:%s\r\n",cjson_str->string,cjson_str->valuestring);
    cjson_str = cJSON_GetObjectItem(cjson_data,"age");//获取名称为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);//将json字符串转化成CJSON结构体类型的数据

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)printf("%s:%s\r\n",personA->string,personA->child->valuestring);
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;

    /* 创建cJSON对象 */
    root = cJSON_CreateObject();    /* 创建一个cJSON对象,要用 cJSON_Delete 释放内存 */
    person = cJSON_CreateObject();  /* 创建子对象 */

    /* 添加json节点 */
    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对象中的内容 */
    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"));

    /* 打印修改后的cJSON对象 */
    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()
{
    /* 定义要解析的JSON对象 */
    char *cJSON_str = "{                      \
	    \"person\":	{                         \
		\"firstName\":	\"Lebron\",           \
		\"lastName\":	\"James\",            \
		\"age\":	    36,                   \
		\"height\":	    203.5                 \
	    },                                    \
        \"team\": \"Lakers\"                  \
    }";

    /* 解析JSON对象 */
    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数组

/*
 * @Description: 
 * @Version: 1.0
 * @Autor: Crystal
 * @Date: 2021-07-02 14:10:40
 * @LastEditors: Crystal
 * @LastEditTime: 2021-07-02 16:51:47
 */
#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"}
    };
    
    /* 创建JSON对象 */
    cJSON *root = cJSON_CreateObject();      // 创建根节点
    cJSON *students = cJSON_CreateObject();  // 创建 students 子节点
    cJSON_AddItemToObject(root, "students", students); // 将子节点添加到根节点中
    cJSON_AddNumberToObject(students, "total", 3);     // 在 students 子节点添加键值对 total   


    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"); // 将 grade 添加到他的父节点中


    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"));
       
    /* 格式化打印创建的带数组的JSON对象 */
    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)
{
    /* 要解析的json对象 */
    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");  // 获取 student 数组
    int stu_arr_size = cJSON_GetArraySize(stu_arr);             // 获取 student 数组中元素的个数
    
    cJSON *grade = cJSON_GetObjectItem(root, "grade");
    
    cJSON *subject_arr = cJSON_GetObjectItem(root, "subject");  // 获取 subject 数组
    int subject_arr_size = cJSON_GetArraySize(subject_arr);     // 获取 subject 数组中元素的个数
    
    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);     // 打印 student 数组中元素的个数
    for(i=0; i<stu_arr_size; ++i)
    {
        item = cJSON_GetArrayItem(stu_arr, i);      // 获取 student 数组中的具体项
        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);     // 打印 subject 数组中元素的个数
    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>  //stat
#include "cJSON.h" 
#define   FILENAME  "./test.json"


/*************
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);用于将字符串解析成json对象,若失败则返回NULL。
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);释放cJSON_Parse()分配出来的内存空间。
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);返回数组中的项数
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);调用cJSON_GetObjectItem()函数,可从cJSON结构体中查找某个子节点名称(键名称),如果查找成功可把该子节点序列化到cJSON结构体中
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);将cJSON实体呈现为用于传输/存储的文本
https://zhuanlan.zhihu.com/p/121064144

要想解析JSON格式,首先需要实现读文件的功能,然后开始JSON字符串的解析。解析文件可以大致分为以下几步骤:

1、在Linux上想要获取文件大小,可以选用stat函数获取文件大小信息
2、申请一段内存,将文件中的文本读取到buffer中
3、通过cJSON_Parse接口解析buffer中的字符串
4、用cJSON_GetObjectItem 接口解析获取指定字段



{
"people":[
{"firstName":"minger","lastName":"minger","email":"123456@163.com","age":23,"height":1.67},
{"firstName":"jinmeng","lastName":"meng","email":"654321@163.com","age":18,"height":1.177},
{"email":"7891011@126.com","firstName":"chen","lastName":"jun","age":26,"height":1.75}
]
} 
*************/
 



//实现了结构体数组的解析
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");  // 获取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"); // 获取json对象中的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}};  

  /*get file size*/
    size_t size = get_file_size(filename);
    if(0 == size)
    {
        printf("get_file_size failed!!!\n");
    }
        
    /*malloc memory*/
    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;  
}  



/******************
解析一个结构体,下面咱看看这类型的结构体怎么解。
{
         "person":
         {
                   "firstName":"minger",
                   "lastName":"ming",
                   "email":"12345678@163.com",
                   "age":18,
                   "height":1.77
         }        
}

需要用到接口函数

cJSON*cJSON_Parse(const char *value); 
cJSON*cJSON_GetObjectItem(cJSON *object,const char *string);
voidcJSON_Delete(cJSON *c); 
解析一个结构体

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;  
}  



********************/


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;

    /* 创建一个JSON数据对象(链表头结点) */
    cjson_test = cJSON_CreateObject();

    /* 添加一条字符串类型的JSON数据(添加一个链表节点) */
    cJSON_AddStringToObject(cjson_test, "name", "mculover666");

    /* 添加一条整数类型的JSON数据(添加一个链表节点) */
    cJSON_AddNumberToObject(cjson_test, "age", 22);

    /* 添加一条浮点类型的JSON数据(添加一个链表节点) */
    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);

    /* 添加一个嵌套的JSON数据(添加一个链表节点) */
    cjson_address = cJSON_CreateObject();
    cJSON_AddStringToObject(cjson_address, "country", "China");
    cJSON_AddNumberToObject(cjson_address, "zip-code", 111111);
    cJSON_AddItemToObject(cjson_test, "address", cjson_address);

     /* 解析嵌套json数据 */
    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);

    /* 添加一个数组类型的JSON数据(添加一个链表节点) */
    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);

    /* 添加一个值为 False 的布尔类型的JSON数据(添加一个链表节点) */
    cJSON_AddFalseToObject(cjson_test, "student");

    /* 打印JSON对象(整条链表)的所有数据 */
    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();
      // 添加key-value
    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);
  
      // obj中添加key - value
      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);/* Read a file, parse, render back, etc. */ 
 
int main(int argc, char **argv)  
{  
 
//  dofile("json_str1.txt"); 
//  dofile("json_str2.txt"); 
    dofile("json_str3.txt");  
 
 return 0;  
}  
 
//parse a key-value pair 
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;  
}  
 
//parse a object to struct 
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;  
}  
 
//parse a struct array 
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;  
}  
 
// Read a file, parse, render back, etc. 
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);  
 
//  char str_name[40]; 
//  int ret = cJSON_to_str(data, str_name); 
 
//  people person; 
//  int ret = cJSON_to_struct(data, &person); 
 
    people worker[3]={{0}};  
    cJSON_to_struct_array(data, worker);  
 
    free(data);  
}  

  C++知识库 最新文章
【C++】友元、嵌套类、异常、RTTI、类型转换
通讯录的思路与实现(C语言)
C++PrimerPlus 第七章 函数-C++的编程模块(
Problem C: 算法9-9~9-12:平衡二叉树的基本
MSVC C++ UTF-8编程
C++进阶 多态原理
简单string类c++实现
我的年度总结
【C语言】以深厚地基筑伟岸高楼-基础篇(六
c语言常见错误合集
上一篇文章      下一篇文章      查看所有文章
加:2022-04-22 18:17:37  更:2022-04-22 18:21:38 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 21:54:45-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码