这篇文章详细介绍了如何使用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