cJSON:構建JSON

eiSouthBoy發表於2024-07-02

使用cJSON庫構建比較簡單的JSON型別:

create_json.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "cJSON.h"


static int create_json_type_1(void)
{
    char *json_str = NULL;
    cJSON *root = NULL;
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "name", cJSON_CreateString("ZhangSan"));
    cJSON_AddItemToObject(root, "age", cJSON_CreateNumber(18));

    json_str = cJSON_Print(root);
    printf("%s\n\n", json_str);

    if (NULL != json_str)
        free(json_str);
    if (NULL != root)
        cJSON_Delete(root);

    return 0;
}

static int create_json_type_2(void)
{    
    char *json_str = NULL;
    cJSON *root = NULL;
    cJSON *score = NULL;

    score = cJSON_CreateObject();
    cJSON_AddItemToObject(score, "name", cJSON_CreateString("LiSi"));
    cJSON_AddItemToObject(score, "math", cJSON_CreateNumber(100));
    cJSON_AddItemToObject(score, "english", cJSON_CreateNumber(90));

    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "score", score);

    json_str = cJSON_Print(root);
    printf("%s\n\n", json_str);

    if (NULL != json_str)
        free(json_str);
    if (NULL != root)
        cJSON_Delete(root);

    return 0;
}

static int create_json_type_3(void)
{
    int count = 0;
    char *json_str = NULL;
    cJSON *root = NULL;
    cJSON *fruit = NULL;
    const char *array[] = {
        "apple", "banana", "orange", "peach"
    };


    count = sizeof(array) / sizeof(array[0]);
    fruit = cJSON_CreateStringArray(array, count);

    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "fruit", fruit);

    json_str = cJSON_Print(root);
    printf("%s\n\n", json_str);

    if (NULL != json_str)
        free(json_str);
    if (NULL != root)
        cJSON_Delete(root);

    return 0;
}

static int create_json_type_4(void)
{
    char *json_str = NULL;
    cJSON *root = NULL;
    cJSON *item1 = NULL;
    cJSON *item2 = NULL;
    cJSON *language = NULL;

    item1 = cJSON_CreateObject();
    cJSON_AddItemToObject(item1, "Chinese", cJSON_CreateNumber(100));

    item2 = cJSON_CreateObject();
    cJSON_AddItemToObject(item2, "English", cJSON_CreateNumber(100));

    language = cJSON_CreateArray();
    cJSON_AddItemToArray(language, item1);
    cJSON_AddItemToArray(language, item2);

    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "language", language);

    json_str = cJSON_Print(root);
    printf("%s\n\n", json_str);

    if (NULL != json_str)
        free(json_str);
    if (NULL != root)
        cJSON_Delete(root);

    return 0;
}

int main(int argc, char *argv[])
{
    /* 形式一 */
    create_json_type_1();

    /* 形式二 */
    create_json_type_2();

    /* 形式三 */
    create_json_type_3();

    /* 形式四 */
    create_json_type_4();

    return 0;
}
  • 形式一

  • 形式二

  • 形式三

  • 形式四

相關文章