Skip to content

JSON 解析的使用

cJSON 参考文档

1.需要引入的库组件:

cmake
idf_component_register(SRCS "json.c"
                       PRIV_REQUIRES json
                       INCLUDE_DIRS "")

2. 引入头文件

c
#include "cJSON.h"

3. 代码示例

1.将字符串解析为 JSON 对象

c
    // 解析 JSON 字符串
    char json_str[] = "{\"name\":\"张三\",\"age\":18,\"hobbies\":[\"reading\",\"swimming\"]}";
    cJSON *root = cJSON_Parse(json_str);
    if (root == NULL)
    {
        printf("JSON parse error.\n");
        return -1;
    }

    cJSON *name = cJSON_GetObjectItem(root, "name");
    cJSON *age = cJSON_GetObjectItem(root, "age");
    cJSON *hobbies = cJSON_GetObjectItem(root, "hobbies");

    printf("Name: %s\n", name->valuestring);
    printf("Age: %d\n", age->valueint);

    int hobbies_size = cJSON_GetArraySize(hobbies);
    printf("Hobbies: ");
    for (int i = 0; i < hobbies_size; i++)
    {
        cJSON *hobby = cJSON_GetArrayItem(hobbies, i);
        printf("%s ", hobby->valuestring);
    }
    printf("\n");

    cJSON_Delete(root);

2.将 JSON 对象转换为字符串

c
    char json_str[] = "{\"name\":\"张三\",\"age\":18,\"hobbies\":[\"reading\",\"swimming\"]}";
    cJSON *root = cJSON_Parse(json_str);
    if (root == NULL)
    {
        printf("JSON parse error.\n");
        return -1;
    }

    cJSON *name = cJSON_GetObjectItem(root, "name");
    cJSON *age = cJSON_GetObjectItem(root, "age");
    cJSON *hobbies = cJSON_GetObjectItem(root, "hobbies");

    name->valuestring = "李四";
    age->valueint = 20;

    cJSON_AddArrayToObject(hobbies, cJSON_CreateString("coding"));

    char *new_json_str = cJSON_Print(root);
    printf("New JSON string: %s\n", new_json_str);

    cJSON_Delete(root);
    free(new_json_str);

cJSON_Print(root); 函数将 JSON 对象转换为字符串,并返回一个指向该字符串的指针。 这个生成的字符串,是格式化后的。生成的字符串类似于:

json
{
    "name": "张三",
    "age": 18,
    "hobbies": [
        "reading",
        "swimming"
    ]
}

使用 cJSON_PrintUnformatted(cJSON *item) 函数将 cJSON 结构体序列化为未格式化的 JSON 字符串. 未格式化的 JSON 字符串是指生成的 JSON 数据是紧凑的,没有多余的空白字符(如空格、换行符、制表符等)。它是一个连续的字符串,所有内容紧密相连,没有缩进或换行。

json
{"name":"张三","age":18,"hobbies":["reading","swimming"]}

这种方式,适合保存到文件中,节省空间。

3.生成JSON数据

以下是使用CJSON库生成JSON数据的基本步骤:

  1. 使用cJSON_CreateObject函数创建一个JSON对象。
  2. 使用cJSON_AddItemToObject函数将键值对添加到JSON对象中。
  3. 使用相应的cJSON_Create...函数创建值。
  4. 使用cJSON_Print函数将JSON对象转换为JSON字符串。 以下是一个示例代码演示如何生成JSON数据:

假如要生成如下的JSON数据:

json
{
	"msg": "sucess",
	"logs": [{
		"name": "abc",
		"age": 1
	}, {
		"name": "abc",
		"age": 1
	}, {
		"name": "abc",
		"age": 1
	}]
}
c
#include <stdio.h>
#include "cJSON.h"

int main() {
 // 创建根JSON对象
    cJSON *root = cJSON_CreateObject();
    if (root == NULL) {
        fprintf(stderr, "Failed to create root object\n");
        return 1;
    }

    // 添加msg字段
    cJSON_AddStringToObject(root, "msg", "sucess");  // 

    // 创建logs数组
    cJSON *logs_array = cJSON_CreateArray();
    if (logs_array == NULL) {
        cJSON_Delete(root);
        fprintf(stderr, "Failed to create array\n");
        return 1;
    }

    // 添加3个相同结构的日志对象
    for (int i = 0; i < 3; i++) {
        cJSON *log_entry = cJSON_CreateObject();
        if (log_entry == NULL) {
            cJSON_Delete(root);
            fprintf(stderr, "Failed to create log entry\n");
            return 1;
        }

        // 添加name和age字段
        cJSON_AddStringToObject(log_entry, "name", "abc");  // 
        cJSON_AddNumberToObject(log_entry, "age", 1);       // 

        // 将日志对象添加到数组
        cJSON_AddItemToArray(logs_array, log_entry);        // 
    }

    // 将数组挂载到根对象
    cJSON_AddItemToObject(root, "logs", logs_array);         // 

    // 生成JSON字符串并输出
    char *json_str = cJSON_Print(root);                     // 
    if (json_str != NULL) {
        printf("%s\n", json_str);
        free(json_str);
    } else {
        fprintf(stderr, "Failed to print JSON\n");
    }

    // 清理内存
    cJSON_Delete(root);                                      // 

    return 0;
}

说明

  1. cJSON_CreateObject函数用于创建一个JSON对象。
  2. cJSON_AddStringToObject函数用于向JSON对象中添加字符串字段。
  3. cJSON_AddNumberToObject函数用于向JSON对象中添加数值字段。
  4. cJSON_CreateArray函数用于创建一个JSON数组。
  5. cJSON_AddItemToArray函数用于将JSON对象添加到JSON数组中。
  6. cJSON_AddItemToObject函数用于将JSON数组挂载到JSON对象中。
  7. cJSON_Print函数用于将JSON对象转换为JSON字符串。
  8. cJSON_Delete函数用于清理内存。

对于 cJSON的对象,无法中间插入了多少对象。最后,只需要调用 cJSON_Delete(root); 即可。