Cjson common API usage summary

json

  JSON (JavaScript Object Notation) is a lightweight data exchange format widely used in front-end and back-end data transmission and storage. In C language, we can use cjson library to process JSON data. This question summarizes the usage of various common APIs in the cjson library, including assembling JSON (including objects, arrays, strings, etc.) and parsing JSON (parsing objects, arrays, strings, etc.).

1. Introduction to cjson library

  cjson is a lightweight C library for manipulating JSON data. It provides an easy-to-use API that can easily convert data in C language into JSON format, and parse data in JSON format into data in C language.

2. Assembly of JSON objects

2.1 Assembling JSON objects

  To assemble a JSON object, the following API can be used:

//先创建一个cJSON对象头指针
cJSON *cJSON_CreateObject(void);
//添加一个对象到另一个对象,实现嵌套
void cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);

Precautions:

  • After the call cJSON_CreateObject, the returned pointer needs to be cJSON_Deletefreed through memory to prevent memory leaks.
  • Use to cJSON_AddItemToObjectadd each sub-item to the JSON object, where stringthe key name of the sub-item itemis the value of the sub-item, which can be numbers, strings, arrays and other JSON types.

Example:

{
“age”:30
“name” :“John”
“is_student”:1
}

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

int main() {
    
    
    // 组装JSON对象
    cJSON *jsonObj = cJSON_CreateObject();
    
    // 添加数字到JSON对象中
    cJSON_AddNumberToObject(jsonObj, "age", 30);
    
    // 添加字符串到JSON对象中
    cJSON_AddStringToObject(jsonObj, "name", "John");
    
    // 添加布尔值到JSON对象中,这里用1表示true
    cJSON_AddBoolToObject(jsonObj, "is_student", 1);

    // 将JSON对象转换成字符串会开辟一个新内存,调用此函数记得手动释放
    char *jsonStr = cJSON_Print(jsonObj);
    printf("JSON Object:\n%s\n", jsonStr);

    // 释放JSON对象的内存
    cJSON_Delete(jsonObj);
    
    // 释放JSON字符串的内存
    free(jsonStr);

    return 0;
}

2.2 Assemble JSON array

To assemble a JSON array, the following API can be used:

cJSON *cJSON_CreateArray(void);
void cJSON_AddItemToArray(cJSON *array, cJSON *item);

Precautions:

  • After the call cJSON_CreateArray, the returned pointer needs to be cJSON_Deletefreed through memory to prevent memory leaks.
  • If the cJSON_CreateArray array object is added to other objects as sub-objects, just release the total JSON header.
  • Use cJSON_AddItemToArrayto add each sub-item to the JSON array, itemwhich is the value of the sub-item, which can be other JSON types such as numbers, strings, and objects.

Example:

{ "logList": [{ "logName": "f1", "logSize": 1357, "logTime": "2023-07-24 15:19:25" } ...//can be added ] }







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

int main() {
    
    
	// 创建 JSON 格式的根对象
	cJSON *root = cJSON_CreateObject();
    cJSON *jsonArray = cJSON_CreateArray();
    //创建子对象
    cJSON *logEntry = cJSON_CreateObject();

	cJSON_AddStringToObject(logEntry, "logName", filename);
	cJSON_AddStringToObject(logEntry, "logSize", 100);
	cJSON_AddStringToObject(logEntry, "logTime","2023-07-24 15:19:25");
	//对象的相互嵌套不受顺序影响
	//将logentry插入到jsonarray数组中
	cJSON_AddItemToArray(jsonArray , logEntry);
	//将数组插入到跟对象
	cJSON_AddItemToObject(root, "jsonArray ", jsonArray );
    char *jsonStr = cJSON_Print(root);
    printf("JSON Array:\n%s\n", jsonStr);

    cJSON_Delete(root); // 释放root内存
    free(jsonStr); // 释放jsonStr内存
    return 0;
}

3. Parsing of JSON objects

3.1 Parsing JSON objects

To parse objects in JSON, the following APIs can be used:

cJSON *cJSON_Parse(const char *value);
cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string);

Precautions:

  • After the call cJSON_Parse, the returned pointer needs to be cJSON_Deletefreed through memory to prevent memory leaks.
  • Use to cJSON_GetObjectItemget the sub-item in the JSON object according to the key name.

Example:

{
“age”:30
“name” :“John”
“is_student”:true
}

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

int main() {
    
    
    const char *jsonStr = "{\"name\":\"John\",\"age\":30,\"is_student\":true}";
    cJSON *jsonObj = cJSON_Parse(jsonStr);

    if (jsonObj != NULL) {
    
    
    	//解析跟每个子对象的顺序无关
        cJSON *nameObj = cJSON_GetObjectItem(jsonObj, "name");
        cJSON *ageObj = cJSON_GetObjectItem(jsonObj, "age");
        cJSON *isStudentObj = cJSON_GetObjectItem(jsonObj, "is_student");

        if (nameObj != NULL && cJSON_IsString(nameObj)) {
    
    
            printf("Name: %s\n", nameObj->valuestring);
        }
        if (ageObj != NULL && cJSON_IsNumber(ageObj)) {
    
    
            printf("Age: %d\n", ageObj->valueint);
        }
        if (isStudentObj != NULL && cJSON_IsBool(isStudentObj)) {
    
    
            printf("Is Student: %s\n", isStudentObj->valueint ? "true" : "false");
        }
        cJSON_Delete(jsonObj); // 释放jsonObj内存
    } else {
    
    
        printf("JSON parsing failed!\n");
    }

    return 0;
}

3.2 Parsing JSON array

To parse an array in JSON, you can use the following API:

cJSON *cJSON_Parse(const char *value);
cJSON *cJSON_GetArrayItem(const cJSON *array, int index);

Precautions:

  • After the call cJSON_Parse, the returned pointer needs to be cJSON_Deletefreed through memory to prevent memory leaks.
  • Use to cJSON_GetArrayItemget the subitems in the JSON array by index.

Example:

{
[ apple,
123,
true
]
}

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

int main() {
    
    
    const char *jsonStr = "[\"apple\", 123, true]";
    cJSON *jsonArray = cJSON_Parse(jsonStr);

    if (jsonArray != NULL && cJSON_IsArray(jsonArray)) {
    
    
        int arraySize = cJSON_GetArraySize(jsonArray);
        for (int i = 0; i < arraySize; i++) {
    
    
            cJSON *item = cJSON_GetArrayItem(jsonArray, i);
            if (cJSON_IsString(item)) {
    
    
                printf("Array Item %d: %s\n", i, item->valuestring);
            } else if (cJSON_IsNumber(item)) {
    
    
                printf("Array Item %d: %d\n", i, item->valueint);
            } else if (cJSON_IsBool(item)) {
    
    
                printf("Array Item %d: %s\n", i, item->valueint ? "true" : "false");
            }
        }
        cJSON_Delete(jsonArray

); // 释放jsonArray内存
    } else {
    
    
        printf("JSON parsing failed!\n");
    }

    return 0;
}

Guess you like

Origin blog.csdn.net/ZBraveHeart/article/details/132037970