#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 字符串内存。