cJSON数据的解析和添加,附上完整代码,方便大家学习。

JSON数据格式简答

单个JSON

下面先贴上一个c语言下的json文件的样式。下面的JSON样式很全,既有了子键,而且有了数组,对于初学者相对来说比较全面。这里先注意一下 最开头的中括号 “[]”,下面解析JSON的时候会介绍到。用下面的代码做测试学习的时候,可以将首尾的中括号去掉,理解一下。

const char *message =
"[{                              \
    \"name\":\"mculover666\",   \
    \"age\": 22,                \
    \"weight\": 55.5,           \
    \"address\":                \
        {                       \
            \"country\": \"China\",\
            \"zip-code\": 111111\
        },                      \
    \"skill\": [\"c\", \"Java\", \"Python\"],\
    \"student\": false          \
}]								\
";

下面是一段正常的JSON数据,更易查看。

[{                              
    "name":"mculover666",   
    "age": 22,                
    "weight": 55.5,           
    "address":                
        {                       
            "country": "China",
            "zip-code": 111111
        },                      
    "skill": ["c", "Java", "Python"],
    "student": false          
}];

多个JSON

单个JSON和多个JSON块的不同就是需要用 逗号 将各个JSON隔开,并且每个JSON都需要用 {} 隔开。

const char *message =
"[{                              \
    \"name\":\"mculover666\",   \
    \"age\": 22,                \
    \"weight\": 55.5,           \
    \"address\":                \
        {                       \
            \"country\": \"China\",\
            \"zip-code\": 111111\
        },                      \
    \"skill\": [\"c\", \"Java\", \"Python\"],\
    \"student\": false          \
},								\
	{                           \
    \"name\":\"dhn\",			\
    \"age\": 23,                \
    \"weight\": 72.6,           \
    \"address\":                \
        {                       \
            \"country\": \"China\",\
            \"zip-code\": 222222\
        },                      \
    \"skill\": [\"c\", \"linux\", \"Python\"],\
    \"student\": true          \
}]";

下面同样贴上正常的JSON样式,便于观看。

[{                              
    "name":"mculover666",   
    "age": 22,                
    "weight": 55.5,           
    "address":                
        {                       
            "country": "China",
            "zip-code": 111111
        },                      
    "skill": ["c", "Java", "Python"],
    "student": false          
},								
	{                           
    "name":"dhn",			
    "age": 23,                
    "weight": 72.6,           
    "address":                
        {                       
            "country": "China",
            "zip-code": 222222
        },                      
    "skill": ["c", "linux", "Python"],
    "student": true          
}]";

cJSON解析数据及打印显示

JSON数据解析和打印

#include <stdio.h>
#include <iostream>
using namespace std;
#include "../cJson/cJSON.h"

const char *message =
"[{                              \
    \"name\":\"mculover666\",   \
    \"age\": 22,                \
    \"weight\": 55.5,           \
    \"address\":                \
        {                       \
            \"country\": \"China\",\
            \"zip-code\": 111111\
        },                      \
    \"skill\": [\"c\", \"Java\", \"Python\"],\
    \"student\": false          \
},								\
	{                           \
    \"name\":\"dhn\",			\
    \"age\": 23,                \
    \"weight\": 72.6,           \
    \"address\":                \
        {                       \
            \"country\": \"China\",\
            \"zip-code\": 222222\
        },                      \
    \"skill\": [\"c\", \"linux\", \"Python\"],\
    \"student\": true          \
}]";

//
//const char *message =
//"[{                              \
//    \"name\":\"mculover666\",   \
//    \"age\": 22,                \
//    \"weight\": 55.5,           \
//    \"address\":                \
//        {                       \
//            \"country\": \"China\",\
//            \"zip-code\": 111111\
//        },                      \
//    \"skill\": [\"c\", \"Java\", \"Python\"],\
//    \"student\": false          \
//}]								\
//";

int main(){
	cJSON* cjson_data = 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;
	cJSON* cjson_student = NULL;
	int    skill_array_size = 0, i = 0;
	cJSON* cjson_skill_item = NULL;
	/* 解析整段JSO数据 */
	cjson_data = cJSON_Parse(message);
	if (cjson_data == NULL){
	//< 当JSON数据格式有错误的时候就会来到这里
		cJSON_Delete(cjson_data);
		cout << "parse json fail!" << endl;
		return -1;
	}
	//< 下面提供了两种打印数据的方法,结果会在下面贴图显示
	cout << "有格式的方式打印Json:" << endl;
	char* without_format_print = cJSON_Print(cjson_data);
	cout << without_format_print << endl;
	free(without_format_print);
	cout << "无格式的方式打印Json:" << endl;
	cout << cJSON_PrintUnformatted(cjson_data) << endl;
//< !!!!!!! 这里很重要,一定要把打印返回的结果释放掉,否则会造成内存泄漏 !!!!!!!

	//< 这里是错误的写法,因为不能直接从数据中直接寻找name的键,需要将子JSON先解析出来然后在解析。
	//< 还记得上面写的 中括号的问题吗 就在这里 【】,如果不加中括号这里是可以使用的,结果会在下面贴图。
	cjson_name = cJSON_GetObjectItem(cjson_data, "name");
	//cout << cjson_name->valuestring;

	int tint = cJSON_GetArraySize(cjson_data);
	cJSON* arr_item = cjson_data->child;//子对象
	for (int i = 0; i < tint; i++) {
		cjson_name = cJSON_GetObjectItem(arr_item, "name");
		cjson_age = cJSON_GetObjectItem(arr_item, "age");
		cjson_weight = cJSON_GetObjectItem(arr_item, "weight");
		cout << cjson_name->valuestring << "  " << cjson_age->valueint << "   " << cjson_weight->valuedouble << endl;

		/* 解析子JSON */
		cjson_address = cJSON_GetObjectItem(arr_item, "address");
		cjson_address_country = cJSON_GetObjectItem(cjson_address, "country");
		cjson_address_zipcode = cJSON_GetObjectItem(cjson_address, "zip-code");
		cout << cjson_address_country->valuestring << "  " << cjson_address_zipcode->valueint << endl;

		/* 解析数组 */
		cjson_skill = cJSON_GetObjectItem(arr_item, "skill");
		skill_array_size = cJSON_GetArraySize(cjson_skill);
		cout << "skill:[";
		for (int j = 0; j < skill_array_size; j++){
			cjson_skill_item = cJSON_GetArrayItem(cjson_skill, j);
			cout << cjson_skill_item->valuestring << ",";
		}
		cout << "\b]" << endl;

		/* 解析布尔型数据 */
		cjson_student = cJSON_GetObjectItem(arr_item, "student");
		cout << (cjson_student->valueint == 0 ? "false" : "true") << endl;

		arr_item = arr_item->next;
	}

	cJSON_Delete(cjson_data);
	return 0;
}

有格式下的数据打印
在这里插入图片描述
无格式下的数据打印,相比于有格式的打印,此打印方法更加节省空间。
在这里插入图片描述

!!!!!!!,注意:一定要记得释放内存。

上面对中括号的解答。若加了中括号,利用上述代码块的单个JSON数据的解析。
在这里插入图片描述
下面是程序完整的运行结果
在这里插入图片描述

注:以上都是对已知的数据格式进行解析,若不知道文件的数据格式,可以利用cJSON结构体当中的type进行判断,
在这里插入图片描述
在这里插入图片描述

根据判断的类型,在决定数据的格式。

cJSON添加数据

添加数据比较简单,这里直接附上代码了。

#include <stdio.h>
#include "../cJson/cJSON.h"

int main()
{
	cJSON* cjson_test = NULL;
	cJSON* cjson_address = 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);

	/* 添加一个嵌套的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_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);
	cJSON_Delete(cjson_test);
	return 0;
}

在挣扎一下:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!一定要记得释放内存。
在这里插入图片描述

创作不易,若对您有帮助,请不要吝啬您的点赞呦。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
假设需要解析的JSON数据如下: ``` { "name": "John", "age": 30, "city": "New York", "hobbies": ["reading", "traveling", "swimming"], "education": { "degree": "Master", "major": "Computer Science" } } ``` 使用cJSON库进行解析的示例代码如下: ```c #include <stdio.h> #include <stdlib.h> #include "cJSON.h" int main() { char *json_str = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\",\"hobbies\":[\"reading\",\"traveling\",\"swimming\"],\"education\":{\"degree\":\"Master\",\"major\":\"Computer Science\"}}"; cJSON *root = cJSON_Parse(json_str); if (root == NULL) { printf("Error before: [%s]\n", cJSON_GetErrorPtr()); return 1; } cJSON *name = cJSON_GetObjectItemCaseSensitive(root, "name"); if (cJSON_IsString(name) && (name->valuestring != NULL)) { printf("Name: %s\n", name->valuestring); } cJSON *age = cJSON_GetObjectItemCaseSensitive(root, "age"); if (cJSON_IsNumber(age)) { printf("Age: %d\n", age->valueint); } cJSON *city = cJSON_GetObjectItemCaseSensitive(root, "city"); if (cJSON_IsString(city) && (city->valuestring != NULL)) { printf("City: %s\n", city->valuestring); } cJSON *hobbies = cJSON_GetObjectItemCaseSensitive(root, "hobbies"); if (cJSON_IsArray(hobbies)) { int i, size = cJSON_GetArraySize(hobbies); printf("Hobbies:\n"); for (i = 0; i < size; i++) { cJSON *item = cJSON_GetArrayItem(hobbies, i); if (cJSON_IsString(item) && (item->valuestring != NULL)) { printf(" %s\n", item->valuestring); } } } cJSON *education = cJSON_GetObjectItemCaseSensitive(root, "education"); if (cJSON_IsObject(education)) { cJSON *degree = cJSON_GetObjectItemCaseSensitive(education, "degree"); if (cJSON_IsString(degree) && (degree->valuestring != NULL)) { printf("Education - Degree: %s\n", degree->valuestring); } cJSON *major = cJSON_GetObjectItemCaseSensitive(education, "major"); if (cJSON_IsString(major) && (major->valuestring != NULL)) { printf("Education - Major: %s\n", major->valuestring); } } cJSON_Delete(root); return 0; } ``` 运行结果: ``` Name: John Age: 30 City: New York Hobbies: reading traveling swimming Education - Degree: Master Education - Major: Computer Science ``` 解析过程中,先使用cJSON_Parse函数将JSON字符串解析成一个cJSON对象(即root)。然后,使用cJSON_GetObjectItemCaseSensitive函数分别获取其中的各个成员对象,并使用不同的cJSON类型判断函数(如cJSON_IsString、cJSON_IsNumber、cJSON_IsArray等)判断其类型。最后,使用各自的value获取成员对象的值。最后,使用cJSON_Delete函数释放cJSON对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值