cJSON (C language JSON) library (for embedded serialization and deserialization)

JSON and serialization and deserialization

JSON (JavaScript Object Notation) is a lightweight data interchange format that represents structured data in text that is easy to read and write. The JSON format is widely used to transfer data from one application to another, especially in web applications, as it is compatible with JavaScript, making it easy to exchange data between clients and servers.

JSON data consists of two main structures:

  1. Object : An object is surrounded by a pair of curly braces {}and contains one or more key-value pairs. In each key-value pair, the key is a string, and the value can be a string, number, Boolean value, array, object, or null. Keys and values ​​are separated by colons :, and key-value pairs are separated by commas ,.

    For example:

    {
          
          
        "name": "John",
        "age": 30,
        "isStudent": false
    }
    
  2. Array[] : An array is surrounded by a pair of square brackets and contains one or more values ​​inside. These values ​​can be strings, numbers, Boolean values, objects, arrays, or null. Values ​​in the array are ,separated by commas.

    For example:

    ["apple", "banana", "cherry"]
    

Serialization and deserialization are the processes of converting data from one format to another:

  1. Serialization : Serialization is the process of converting a data structure (such as an object or array) into a JSON string. In programming, this is often used to convert data into a format that can be transmitted over a network or stored in a file.

    For example, in JavaScript, use JSON.stringify()the method to serialize an object or array into a JSON string:

    const data = {
          
           name: "John", age: 30 };
    const jsonString = JSON.stringify(data);
    

    This will generate the following JSON string:

    {
          
          "name":"John","age":30}
    
  2. Deserialization : Deserialization is the process of converting a JSON string back into the original data structure. This is typically used to read JSON data from the network or file and restore it into a data structure that can be used by the program.

    In JavaScript, JSON.parse()you can deserialize a JSON string into a raw object or array using the method:

    const jsonString = '{"name":"John","age":30}';
    const data = JSON.parse(jsonString);
    

    This will restore the JSON string to an object containing the same data.

In short, JSON is a commonly used data format. Serialization and deserialization are important processes for converting data into JSON format and restoring it back to the original data structure for data exchange and persistent storage.

cJSON (C language JSON) library introduction

The cJSON (C JSON) library is a lightweight open source library for parsing and generating JSON data in C.

Warehouse Address:

https://github.com/DaveGamble/cJSON

It provides a simple yet powerful API that enables C language programs to easily process JSON data. Key features of the cJSON library include:

  1. Lightweight : The cJSON library is very small, so it does not add much memory overhead or binary size, making it suitable for embedded systems and resource-constrained environments.

  2. Ease of use : cJSON provides a simple set of API functions that enable users to easily parse and generate JSON data. These APIs include creating JSON objects, arrays, strings, numbers, etc., and parsing JSON data into C language data structures.

  3. Cross-platform : The cJSON library is cross-platform and can run on multiple operating systems and compilers, making it suitable for various C language projects.

  4. Open source : cJSON is open source, allowing users to use and modify it for free, in line with the principles of free software and open source software.

  5. Supports standard JSON format : The cJSON library supports standard JSON format and can correctly handle basic JSON data types such as JSON objects, arrays, strings, numbers, Boolean values, and null.

Here are some basic usage examples of the cJSON library:

Create JSON object and add key-value pairs :

cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "name", "John");
cJSON_AddNumberToObject(root, "age", 30);

Create JSON array and add elements :

cJSON *array = cJSON_CreateArray();
cJSON_AddItemToArray(array, cJSON_CreateString("apple"));
cJSON_AddItemToArray(array, cJSON_CreateString("banana"));

Parse JSON data into C language data structure :

const char *jsonStr = "{\"name\":\"John\",\"age\":30}";
cJSON *root = cJSON_Parse(jsonStr);
const char *name = cJSON_GetObjectItem(root, "name")->valuestring;
int age = cJSON_GetObjectItem(root, "age")->valueint;

Generate JSON string :

char *jsonStr = cJSON_Print(root);

It is important to note that when using the cJSON library, memory allocation and deallocation should be handled carefully to avoid memory leaks. cJSON provides some functions for releasing JSON objects to ensure that the related memory is released correctly after using the JSON data.

The cJSON library is usually used in C language projects where interaction with JSON data is required, such as communicating with APIs, configuration file parsing and generation, etc. Due to its lightweight and ease of use, it is widely used in many C language applications.

cJSON (C language JSON) library usage

There will be a lot of files downloaded, but the only ones that are actually used are cJSON.h cJSON.c

appveyor.yml  cJSON.c  cJSON_Utils.c  CMakeLists.txt   fuzzing  LICENSE  README.md  tests
CHANGELOG.md  cJSON.h  cJSON_Utils.h  CONTRIBUTORS.md  library_config  Makefile  test.c valgrind.supp

Put the file in the project directory and include cJSON.h and you can use it.

Serialization
Introduction to commonly used functions
  1. cJSON_AddNullToObject(cJSON * const object, const char * const name)

    • Function: Add a null value to the JSON object.
    • parameter:
      • object- Target JSON object.
      • name- The name of the key to add (C string).
    • Return value: None.
  2. cJSON_AddTrueToObject(cJSON * const object, const char * const name)

    • Function: Add true value to JSON object.
    • parameter:
      • object- Target JSON object.
      • name- The name of the key to add (C string).
    • Return value: None.
  3. cJSON_AddFalseToObject(cJSON * const object, const char * const name)

    • Function: Add false value to JSON object.
    • parameter:
      • object- Target JSON object.
      • name- The name of the key to add (C string).
    • Return value: None.
  4. cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)

    • Function: Add boolean value to JSON object.
    • parameter:
      • object- Target JSON object.
      • name- The name of the key to add (C string).
      • boolean- The Boolean value to add, non-zero means true, zero means false.
    • Return value: None.
  5. cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)

    • Function: Add numeric value to JSON object.
    • parameter:
      • object- Target JSON object.
      • name- The name of the key to add (C string).
      • number- The double precision floating point number to add.
    • Return value: None.
  6. cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)

    • Function: Add string value to JSON object.
    • parameter:
      • object- Target JSON object.
      • name- The name of the key to add (C string).
      • string- The C string to add.
    • Return value: None.
  7. cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)

    • Function: Add raw JSON string to JSON object. This method allows you to add a raw string that is already valid JSON to the object without additional parsing.
    • parameter:
      • object- Target JSON object.
      • name- The name of the key to add (C string).
      • raw- The raw JSON string to add.
    • Return value: None.
  8. cJSON_AddObjectToObject(cJSON * const object, const char * const name)

    • Function: Create a new JSON object and add it to the parent JSON object as a child object.
    • parameter:
      • object- Target JSON object.
      • name- The name of the key to add (C string).
    • Return value: None.
  9. cJSON_AddArrayToObject(cJSON *const object, const char *const name) :

    • Function: Create a new JSON array and add it to the parent JSON object as a child array.
    • parameter:
      • object- Target JSON object.
      • name- The name of the key to add (C string).
    • Return value: None.
Example code
#include<stdio.h>
#include"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", "SysBent");

    /* 添加一条整数类型的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", 500000);
    cJSON_AddItemToObject(cjson_test, "address", cjson_address);

    /* 添加一个数组类型的JSON数据(添加一个链表节点) */
    cjson_skill = cJSON_CreateArray();
    cJSON_AddItemToArray(cjson_skill, cJSON_CreateString( "C/C++" ));
    cJSON_AddItemToArray(cjson_skill, cJSON_CreateString( "Java" ));
    cJSON_AddItemToArray(cjson_skill, cJSON_CreateString( "Python" ));
    cJSON_AddItemToObject(cjson_test, "skill", cjson_skill);

    /* 添加一个值为 True 的布尔类型的JSON数据(添加一个链表节点) */
    cJSON_AddTrueToObject(cjson_test,"student");

    /* 打印JSON对象(整条链表)的所有数据 */
    str = cJSON_Print(cjson_test);
    printf("JSON String:\n%s\n", str);
    return 0;
}

Compile and run
Please add image description

Deserialization
Introduction to commonly used functions

In the cJSON library, deserialization refers to the process of parsing a JSON string into a C language data structure. The cJSON library provides some functions to implement this process, among which the most commonly used functions are cJSON_Parse(). Here is a detailed explanation of this function and other related functions:

  1. cJSON_Parse(const char *value)

    • Function: Parse JSON string into corresponding JSON object or array.
    • Parameters: value- C string containing JSON data.
    • Return value: Returns a pointer to the parsed JSON object or array. If parsing fails, NULL is returned.

    Example:

    const char* json_str = "{\"name\":\"John\",\"age\":30}";
    cJSON* parsed_json = cJSON_Parse(json_str);
    if (parsed_json != NULL) {
          
          
        // 解析成功,可以继续操作解析后的JSON数据
        // ...
        cJSON_Delete(parsed_json); // 释放内存
    } else {
          
          
        // 解析失败,处理错误
        // ...
    }
    
  2. cJSON_GetObjectItem(const cJSON *object, const char *string)

    • Function: Get the value of the specified key in the JSON object.
    • parameter:
      • object- Target JSON object.
      • string- The name of the key to get the value from (C string).
    • Return value: Returns a JSON object pointing to the value or NULL if the key does not exist.

    Example:

    const cJSON* name_item = cJSON_GetObjectItem(parsed_json, "name");
    if (name_item != NULL) {
          
          
        const char* name = name_item->valuestring;
        printf("Name: %s\n", name);
    }
    
  3. cJSON_GetArrayItem(const cJSON *array, int index)

    • Function: Get the element at the specified index position in the JSON array.
    • parameter:
      • array- Target JSON array.
      • index- The index of the element to get (starting from 0).
    • Return value: Returns a JSON object pointing to the element or NULL if the index is out of bounds.

    Example:

    const cJSON* skill_item = cJSON_GetArrayItem(parsed_json, 0);
    if (skill_item != NULL) {
          
          
        const char* skill = skill_item->valuestring;
        printf("Skill 1: %s\n", skill);
    }
    
  4. cJSON_GetArraySize(const cJSON *array)

    • Function: Get the size of the JSON array (number of elements).
    • Parameters: array- Target JSON array.
    • Return value: Returns the size of the array.

    Example:

    int array_size = cJSON_GetArraySize(parsed_json);
    printf("Array Size: %d\n", array_size);
    

These functions enable you to easily access and extract the values ​​of JSON data for use in C programs after parsing the JSON string. Be sure to release the relevant memory through the function after using the JSON data cJSON_Delete()to avoid memory leaks.

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

int main() {
    
    
    const char* json_str = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
    cJSON* parsed_json = cJSON_Parse(json_str);

    if (parsed_json != NULL) {
    
    
        // 从JSON对象中获取数据
        const char* name = cJSON_GetObjectItem(parsed_json, "name")->valuestring;
        int age = cJSON_GetObjectItem(parsed_json, "age")->valueint;
        const char* city = cJSON_GetObjectItem(parsed_json, "city")->valuestring;

        // 打印获取的数据
        printf("Name: %s\n", name);
        printf("Age: %d\n", age);
        printf("City: %s\n", city);

        // 释放内存
        cJSON_Delete(parsed_json);
    } else {
    
    
        printf("JSON parsing failed.\n");
    }

    return 0;
}

Compile and run
Please add image description

Precautions for use

When using the cJSON library, special attention needs to be paid to memory management issues to avoid memory leaks or memory overflows. Here are some memory issues that may be involved when using the cJSON library and suggestions on how to deal with them:

  1. Memory allocation :

    • The cJSON library involves memory allocation when creating and manipulating JSON objects. You need to make sure you allocate enough memory when using cJSON_CreateObject(), and other creation functions.cJSON_CreateArray()
    • In embedded systems, resources may be limited, so be careful with the amount and timing of memory allocations to avoid running out of memory.
  2. Free memory :

    • cJSON_Delete()The function should be used to free the memory when the JSON object is no longer needed . Otherwise, memory leaks may result.
    • Make sure to free memory for nested JSON objects and array elements to prevent missing any child objects.
  3. Release the serialized string memory :

    • After using cJSON_Print()the function to serialize the JSON object into a string, you need to be responsible for releasing the string memory to avoid memory leaks.
    • Use free()the function to free these string memory.
  4. Error handling :

    • When allocating memory and using cJSON functions, always check whether the returned pointer is NULL. If memory allocation fails or JSON string parsing fails, handle the error situation promptly.
  5. Stack memory and heap memory :

    • Consider the size of JSON objects. Small JSON objects can be allocated on the stack, while large objects may require memory allocation on the heap. Choose the appropriate memory allocation method according to the actual situation.
  6. Nested and circular references :

    • Be careful with circular references when it comes to nested JSON objects. Circular references can cause memory leaks or infinite recursion.
    • Consider using reference counting or other means to manage memory release of nested objects.
  7. Memory pool :

    • For resource-constrained embedded systems, you may consider implementing a memory pool to manage memory allocation for the cJSON library. This can help you better control and optimize memory usage.

In summary, good memory management is very important when using the cJSON library. Be careful with memory allocation, deallocation, and error handling to ensure that your application does not have memory issues when processing JSON data. Also, consider using appropriate memory optimization strategies based on your application needs.
The following is a sample code that demonstrates how to use the cJSON library to create and release JSON objects and handle the memory issues that may be involved:

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

int main() {
    
    
    // 创建一个JSON对象
    cJSON* cjson_object = cJSON_CreateObject();
    
    if (cjson_object != NULL) {
    
    
        // 添加键值对到JSON对象
        cJSON_AddStringToObject(cjson_object, "name", "John");
        cJSON_AddNumberToObject(cjson_object, "age", 30);
        
        // 序列化JSON对象为字符串
        char* json_str = cJSON_Print(cjson_object);
        printf("Serialized JSON:\n%s\n", json_str);
        
        // 释放序列化后的字符串内存
        free(json_str);
        
        // 释放JSON对象内存
        cJSON_Delete(cjson_object);
    } else {
    
    
        printf("Failed to create JSON object.\n");
    }

    return 0;
}

In this example, we first create a JSON object cjson_objectand then add key-value pairs to it. Next, we use cJSON_Print()the function to serialize the JSON object into a string and use free()the function to release the serialized string memory. Finally, we use cJSON_Delete()the function to free the memory of the JSON object.

Please note that this example is only used to demonstrate the basic principles of memory management. In real applications, you may deal with more complex JSON structures, nested objects, and arrays, so more complex memory management strategies are needed to ensure there are no memory leaks or errors.

Guess you like

Origin blog.csdn.net/Systemmax20/article/details/133134737