cJson demo
这篇文章列举出大部分常用cjson调用的demo场景,并列举出对应的打印
1. 创建 JSON 对象并打印
此示例展示了如何创建一个简单的 JSON 对象,并将其打印为 JSON 字符串。
#include <stdio.h>
#include <stdlib.h>
#include <cjson/cJSON.h>
int main() {
    // 创建 JSON 对象
    cJSON *root = cJSON_CreateObject();
    // 向对象中添加数据
    cJSON_AddStringToObject(root, "name", "Alice");
    cJSON_AddNumberToObject(root, "age", 25);
    cJSON_AddBoolToObject(root, "isStudent", 1);
    // 将 JSON 对象打印成字符串
    char *json_string = cJSON_Print(root);
    printf("JSON: \n%s\n", json_string);
    // 清理内存
    free(json_string);
    cJSON_Delete(root);
    return 0;
}
输出:
{
  "name": "Alice",
  "age": 25,
  "isStudent": true
}
2. 创建 JSON 数组并打印
此示例展示了如何创建一个 JSON 数组,并添加一些元素。
#include <stdio.h>
#include <stdlib.h>
#include <cjson/cJSON.h>
int main() {
    // 创建 JSON 数组
    cJSON *array = cJSON_CreateArray();
    // 向数组中添加数据
    cJSON_AddStringToArray(array, "apple");
    cJSON_AddStringToArray(array, "banana");
    cJSON_AddNumberToArray(array, 42);
    // 将 JSON 数组打印成字符串
    char *json_string = cJSON_Print(array);
    printf("JSON Array: \n%s\n", json_string);
    // 清理内存
    free(json_string);
    cJSON_Delete(array);
    return 0;
}
输出:
["apple", "banana", 42]
3. 解析 JSON 字符串并访问数据
此示例展示了如何解析 JSON 字符串,并访问其中的值。
#include <stdio.h>
#include <stdlib.h>
#include <cjson/cJSON.h>
int main() {
    // JSON 字符串
    const char *json_string = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
    // 解析 JSON 字符串
    cJSON *json = cJSON_Parse(json_string);
    if (json == NULL) {
        printf("Error parsing JSON.\n");
        return -1;
    }
    // 获取各个字段的值
    cJSON *name = cJSON_GetObjectItem(json, "name");
    cJSON *age = cJSON_GetObjectItem(json, "age");
    cJSON *city = cJSON_GetObjectItem(json, "city");
    // 输出数据
    if (cJSON_IsString(name)) {
        printf("Name: %s\n", name->valuestring);
    }
    if (cJSON_IsNumber(age)) {
        printf("Age: %d\n", age->valueint);
    }
    if (cJSON_IsString(city)) {
        printf("City: %s\n", city->valuestring);
    }
    // 清理内存
    cJSON_Delete(json);
    return 0;
}
输出:
Name: John
Age: 30
City: New York
4. 修改 JSON 对象
此示例展示了如何修改 JSON 对象中的数据。
#include <stdio.h>
#include <stdlib.h>
#include <cjson/cJSON.h>
int main() {
    // JSON 字符串
    const char *json_string = "{\"name\": \"Alice\", \"age\": 25}";
    // 解析 JSON 字符串
    cJSON *json = cJSON_Parse(json_string);
    if (json == NULL) {
        printf("Error parsing JSON.\n");
        return -1;
    }
    // 修改值
    cJSON *name = cJSON_GetObjectItem(json, "name");
    if (cJSON_IsString(name)) {
        cJSON_SetValuestring(name, "Bob");
    }
    // 添加新字段
    cJSON_AddStringToObject(json, "city", "Los Angeles");
    // 输出修改后的 JSON 对象
    char *json_string_new = cJSON_Print(json);
    printf("Modified JSON: \n%s\n", json_string_new);
    // 清理内存
    free(json_string_new);
    cJSON_Delete(json);
    return 0;
}
输出:
{
  "name": "Bob",
  "age": 25,
  "city": "Los Angeles"
}
5. 嵌套 JSON 对象和数组
此示例展示了如何创建包含嵌套对象和数组的复杂 JSON 数据结构。
#include <stdio.h>
#include <stdlib.h>
#include <cjson/cJSON.h>
int main() {
    // 创建顶层 JSON 对象
    cJSON *root = cJSON_CreateObject();
    // 添加简单数据
    cJSON_AddStringToObject(root, "name", "Alice");
    cJSON_AddNumberToObject(root, "age", 25);
    // 创建一个嵌套的 JSON 对象
    cJSON *address = cJSON_CreateObject();
    cJSON_AddStringToObject(address, "street", "123 Main St");
    cJSON_AddStringToObject(address, "city", "New York");
    cJSON_AddStringToObject(address, "zip", "10001");
    // 将嵌套的对象添加到顶层对象
    cJSON_AddItemToObject(root, "address", address);
    // 创建一个嵌套的 JSON 数组
    cJSON *skills = cJSON_CreateArray();
    cJSON_AddStringToArray(skills, "C");
    cJSON_AddStringToArray(skills, "C++");
    cJSON_AddStringToArray(skills, "Python");
    // 将数组添加到顶层对象
    cJSON_AddItemToObject(root, "skills", skills);
    // 打印最终的 JSON 字符串
    char *json_string = cJSON_Print(root);
    printf("Complex JSON: \n%s\n", json_string);
    // 清理内存
    free(json_string);
    cJSON_Delete(root);
    return 0;
}
输出:
{
  "name": "Alice",
  "age": 25,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "zip": "10001"
  },
  "skills": ["C", "C++", "Python"]
}
6. 从文件中读取 JSON 并解析
此示例展示了如何从文件中读取 JSON 数据并解析它。
#include <stdio.h>
#include <stdlib.h>
#include <cjson/cJSON.h>
char *read_file(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (!file) {
        perror("Failed to open file");
        return NULL;
    }
    // 获取文件大小
    fseek(file, 0, SEEK_END);
    long length = ftell(file);
    fseek(file, 0, SEEK_SET);
    // 读取文件内容
    char *content = (char *)malloc(length + 1);
    if (content) {
        fread(content, 1, length, file);
        content[length] = '\0';  // 确保字符串结尾
    }
    fclose(file);
    return content;
}
int main() {
    // 读取 JSON 文件内容
    const char *filename = "data.json";
    char *file_content = read_file(filename);
    if (!file_content) {
        return -1;
    }
    // 解析 JSON 字符串
    cJSON *json = cJSON_Parse(file_content);
    free(file_content);  // 读取后释放内存
    if (json == NULL) {
        printf("Error parsing JSON.\n");
        return -1;
    }
    // 访问数据
    cJSON *name = cJSON_GetObjectItem(json, "name");
    cJSON *age = cJSON_GetObjectItem(json, "age");
    printf("Name: %s\n", name->valuestring);
    printf("Age: %d\n", age->valueint);
    // 清理内存
    cJSON_Delete(json);
    return 0;
}
7. 将修改后的 JSON 写回文件
此示例展示了如何将修改后的 JSON 对象写回文件。
#include <stdio.h>
#include <stdlib.h>
#include <cjson/cJSON.h>
int write_to_file(const char *filename, cJSON *json) {
    FILE *file = fopen(filename, "w");
    if (!file) {
        perror("Failed to open file for writing");
        return -1;
    }
    // 将 JSON 对象格式化为字符串并写入文件
    char *json_str = cJSON_Print(json);
    if (json_str) {
        fprintf(file, "%s\n", json_str);
        free(json_str);
    }
    fclose(file);
    return 0;
}
int main() {
    // 创建一个简单的 JSON 对象
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "name", "Alice");
    cJSON_AddNumberToObject(root, "age", 25);
    // 写入到文件
    const char *filename = "output.json";
    if (write_to_file(filename, root) != 0) {
        return -1;
    }
    // 清理内存
    cJSON_Delete(root);
    printf("JSON data written to %s\n", filename);
    return 0;
}
总结
这些示例展示了如何在 C 语言中使用 cJSON 库进行常见的 JSON 操作,包括创建、修改、访问、解析和存储 JSON 数据。你可以根据这些基础操作灵活地处理 JSON 数据,构建复杂的 JSON 结构来满足应用需求。










