cJson库的使用

这篇文章详细介绍了如何使用cJSON库来解析和处理JSON数据。首先,文章指导读者如何下载、解压、编译和安装cJSON库。接着,介绍了如何添加动态库路径,以便在编译链接时能够找到cJSON库。文章还提供了makefile文件的示例,用于编译使用cJSON库的代码。最后,通过一个具体的案例,展示了如何使用cJSON库将JSON字符串转换为JSON对象,并遍历和打印出JSON对象的内容。本文内容实用,对于需要使用cJSON库进行JSON处理的开发者来说,具有很高的参考价值。通过遵循本文的步骤,开发者可以轻松地集成cJSON库到他们的项目中,并有效地处理JSON数据。

1.安装cJson

#下载cJSON源代码

wget https://github.com/DaveGamble/cJSON/archive/refs/tags/v1.7.15.tar.gz

# 解压源代码 tar -xzf v1.7.15.tar.gz cd cJSON-1.7.15/

# 配置并编译(通常使用Makefile)

make

# 安装库和头文件

sudo make install

2.添加动态库路径

sudo sh -c 'echo "/usr/local/lib" >> /etc/ld.so.conf'

sudo ldconfig

3.编译代码

makefile 文件内容


main:main.c  
	gcc -o $@ $^ -I/usr/local/include/cjson -L/usr/local/lib -lcjson

执行

make

4.案例

json字符串 转换成 json对象并打印内容

{
    "Data": {
        "Elements": [
            {
                "Category": "可回收垃圾",
                "CategoryScore": 1.0,
                "Rubbish": "塑料饮料瓶",
                "RubbishScore": 1.0
            }
        ],
        "Sensitive": false
    },
    "RequestId": "D1E8EFA7-7C27-5972-A10E-324BBD05273C"
}

 

在这个示例中,我们首先确保json_str是一个有效的JSON字符串。然后,我们使用cJSON_Parse将其解析为cJSON对象。之后,我们使用cJSON_GetObjectItemCaseSensitive来遍历JSON对象的各个层级,并获取我们感兴趣的字段。对于每个字段,我们检查它是否存在,以及它的类型是否正确,然后打印出它的值。

请注意,我们使用了cJSON_IsArray来检查Elements是否真的是一个数组,并且使用了cJSON_GetArraySize


// garbagetest.c
#include <stdio.h>
#include <stdlib.h>
#include "garbage.h"
#include "cJSON.h"

void parseJson(char *json_str)
{
	printf("%s", json_str);
	// 使用cJSON_Parse将字符串转换为cJSON对象
	cJSON *root = cJSON_Parse(json_str);
	if (root == NULL)
	{
		// 解析失败,处理错误
		const char *error_ptr = cJSON_GetErrorPtr();
		if (error_ptr != NULL)
		{
			fprintf(stderr, "Error before: [%s]\n", error_ptr);
		}
		return 1; // 返回错误代码
	}

	// 获取Data对象
	cJSON *data = cJSON_GetObjectItemCaseSensitive(root, "Data");
	if (data == NULL)
	{
		fprintf(stderr, "Cannot find Data item\n");
		cJSON_Delete(root);
		return 1;
	}
	// 获取Elements数组
	cJSON *elements = cJSON_GetObjectItemCaseSensitive(data, "Elements");
	if (elements == NULL || !cJSON_IsArray(elements))
	{
		fprintf(stderr, "Cannot find Elements array\n");
		cJSON_Delete(root);
		return 1;
	}

	// 遍历Elements数组中的每个对象
	int element_count = cJSON_GetArraySize(elements);
	for (int i = 0; i < element_count; i++)
	{
		cJSON *element = cJSON_GetArrayItem(elements, i);
		if (element == NULL)
		{
			continue;
		}

		// 打印Category
		cJSON *category = cJSON_GetObjectItemCaseSensitive(element, "Category");
		if (category && cJSON_IsString(category) && category->valuestring != NULL)
		{
			printf("Category: %s\n", category->valuestring);
		}

		// 打印CategoryScore
		cJSON *category_score = cJSON_GetObjectItemCaseSensitive(element, "CategoryScore");
		if (category_score && cJSON_IsNumber(category_score))
		{
			printf("CategoryScore: %f\n", category_score->valuedouble);
		}
		// 打印Rubbish
		cJSON *Rubbish = cJSON_GetObjectItemCaseSensitive(element, "Rubbish");
		if (category_score && cJSON_IsString(Rubbish) && Rubbish->valuestring != NULL)
		{
			printf("Rubbish: %s\n", Rubbish->valuestring);
		}
		// 打印RubbishScore
		cJSON *RubbishScore_score = cJSON_GetObjectItemCaseSensitive(element, "RubbishScore");
		if (RubbishScore_score && cJSON_IsNumber(RubbishScore_score))
		{
			printf("RubbishScore: %f\n", RubbishScore_score->valuedouble);
		}
		// ... 类似地打印其他字段 ...
	}

	// 打印Sensitive
	cJSON *sensitive = cJSON_GetObjectItemCaseSensitive(data, "Sensitive");
	if (sensitive && cJSON_IsBool(sensitive))
	{
		printf("Sensitive: %s\n", sensitive->valueint ? "true" : "false");
	}

	// 打印RequestId
	cJSON *request_id = cJSON_GetObjectItemCaseSensitive(root, "RequestId");
	if (request_id && cJSON_IsString(request_id) && request_id->valuestring != NULL)
	{
		printf("RequestId: %s\n", request_id->valuestring);
	}

	// 释放cJSON对象占用的内存
	cJSON_Delete(root);
}

int main()
{
	char *json_str = "{\"Data\": {\"Elements\": [{\"Category\": \"干垃圾\",\"CategoryScore\": 0.8855999999999999,\"Rubbish\": \"塑料饮料瓶\",\"RubbishScore\": 0.0}],\"Sensitive\": false},\"RequestId\": \"1AB9E813-3781-5CA2-95A0-1EA334E80663\"}"; 
 
	parseJson(json_str);

	return 0;
}

运行结果

Category: 可回收垃圾
CategoryScore: 1.000000
Rubbish: 塑料饮料瓶
RubbishScore: 1.000000
Sensitive: false
RequestId: 15C6FB95-9057-5226-A761-E0E56BD9FA79

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2023框框

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值