首页 > 解决方案 > 我们如何使用 cJSON 向解析的 JSON 添加新项目?

问题描述

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

{ "messages":[ { "sender":"SERVER","message":"Channel Created" } , { "sender":"Will","message":"Hello Buddies!" } ] }

标签: cjsoncjson

解决方案


解析完 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;
}

推荐阅读