c - 我们如何使用 cJSON 向解析的 JSON 添加新项目?
问题描述
我正在为我的客户端编写一个保存消息的服务器。我使用 cJSON 将它们保存为 JSON 格式 - by Dave Gambler - 并将它们保存在文本文件中。从文件中读取字符串并解析后,如何将新项目添加到我的数组中?JSON 字符串如下所示:
{ "messages":[ { "sender":"SERVER","message":"Channel Created" } , { "sender":"Will","message":"Hello Buddies!" } ] }
解决方案
解析完 json 字符串后,您需要创建一个包含新消息的新对象并将该对象添加到现有数组中。
#include <stdio.h>
#include "cJSON.h"
int main()
{
cJSON *msg_array, *item;
cJSON *messages = cJSON_Parse(
"{ \"messages\":[ \
{ \"sender\":\"SERVER\", \"message\":\"Channel Created\" }, \
{ \"sender\":\"Will\", \"message\":\"Hello Buddies!\" } ] }");
if (!messages) {
printf("Error before: [%s]\n", cJSON_GetErrorPtr());
}
msg_array = cJSON_GetObjectItem(messages, "messages");
// Create a new array item and add sender and message
item = cJSON_CreateObject();
cJSON_AddItemToObject(item, "sender", cJSON_CreateString("new sender"));
cJSON_AddItemToObject(item, "message", cJSON_CreateString("new message"));
// insert the new message into the existing array
cJSON_AddItemToArray(msg_array, item);
printf("%s\n", cJSON_Print(messages));
cJSON_Delete(messages);
return 0;
}
推荐阅读
- python - Django/Play 框架:阐明 HTTP 分块/流式处理的情况
- javascript - 使用 hapi-auth-basic
- node.js - mongodb 只有一些集合正在返回数据,而有些则不是,尽管它们使用 nodeJS 在同一个数据库上
- wso2 - 使用在 WSO2 API 管理器中创建的 API 访问 WSO2IS XACML 策略。无法访问 XACML 策略
- angular - 为什么我的订阅函数正在打印一个对象而不是 http 请求的结果?
- android - Ionic 4 Rest api 调用在有和没有代理的设备上都不起作用。出现未知错误
- chatbot - 如何在 recast.ai 聊天机器人中将用户响应写入谷歌表格
- python - 如何使用“请求”模块python进行简单的快速请求?
- mongodb - 如何从 Mongoengine 中的 ReferenceField 访问其他类元素
- c# - 将参数传递给任务会引发转换类型错误