cJSON

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

int main() {
    const char *payloadptr = "{\"name\":\"John Doe\",\"age\":30,\"msg\":\"Hello, world!\"}";

    cJSON *root = cJSON_Parse(payloadptr);
    if (root == NULL) {
        printf("Error parsing JSON: %s\n", cJSON_GetErrorPtr());
        return 1;
    }

    cJSON *name = cJSON_GetObjectItem(root, "name");
    if (name != NULL) {
        printf("%s = %s\n", name->string, name->valuestring);
    }

    cJSON *age = cJSON_GetObjectItem(root, "age");
    if (age != NULL) {
        printf("%s = %d\n", age->string, age->valueint);
    }

    cJSON *msg = cJSON_GetObjectItem(root, "msg");
    if (msg != NULL) {
        printf("%s = %s\n", msg->string, msg->valuestring);
    }

    cJSON_Delete(root);

    return 0;
}

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

int main() {
    // 创建一个空的 cJSON 对象作为根节点
    cJSON *root = cJSON_CreateObject();
    if (root == NULL) {
        printf("Error creating cJSON object.\n");
        return 1;
    }

    // 添加字段到 cJSON 对象中
    cJSON_AddStringToObject(root, "name", "John Doe");
    cJSON_AddNumberToObject(root, "age", 30);
    cJSON_AddStringToObject(root, "msg", "Hello, world!");

    // 序列化 cJSON 对象为 JSON 字符串
    char *json_str = cJSON_Print(root);
    if (json_str == NULL) {
        cJSON_Delete(root);
        printf("Error printing cJSON object.\n");
        return 1;
    }

    // 输出序列化后的 JSON 字符串
    printf("%s\n", json_str);

    // 释放 cJSON 对象和 JSON 字符串
    cJSON_Delete(root);
    free(json_str);

    return 0;
}

序列化的解释代码:

创建 cJSON 对象:

使用 cJSON_CreateObject() 创建一个空的 cJSON 对象作为根节点。

添加字段:

使用 cJSON_AddStringToObject() 添加 "name" 字段和对应的字符串值 "John Doe"。

使用 cJSON_AddNumberToObject() 添加 "age" 字段和对应的数值 30。

使用 cJSON_AddStringToObject() 添加 "msg" 字段和对应的字符串值 "Hello, world!"。

序列化为 JSON 字符串:

使用 cJSON_Print() 将 cJSON 对象序列化为 JSON 字符串。这个函数会动态分配内存来存储 JSON 字符串。

输出 JSON 字符串:

使用 printf() 输出序列化后的 JSON 字符串到标准输出。

释放资源:

使用 cJSON_Delete() 删除 cJSON 对象及其子对象。

使用 free() 释放之前由 cJSON_Print() 分配的 JSON 字符串内存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值