我们如何使用cJSON将新项目添加到已解析的JSON?

问题描述 投票:0回答:1

我正在为客户端的邮件服务器编程。我使用cJSON将它们保持为JSON格式-by Dave Gambler-并将它们保存在文本文件中。从文件中读取字符串并对其进行解析后,如何将新项目添加到我的数组中?JSON字符串如下所示:

{“ messages”:[{“ sender”:“ SERVER”,“ message”:“已创建频道”},{“ sender”:“ Will”,“ message”:“ Hello Buddies!” }]}

c json cjson
1个回答
0
投票

解析您的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;
}
© www.soinside.com 2019 - 2024. All rights reserved.