cJSON c++ - add item object

放肆的年华 提交于 2020-06-18 13:09:06

问题


I'm using cJSON Library. For a body example request with JSON like this:

{
  "user": {
    "name":"user name",
    "city":"user city"  
  }  
}

I add the objects like this and its work:

cJSON *root;
cJSON *user;

root = cJSON_CreateObject();
cJSON_AddItemToObject(root,"user", user = cJson_CreateObject());
cJSON_AddStringToObject(user, "name", name.c_str());
cJSON_AddStringToObject(user, "city", city.c_str());

But now i have a body json little different:

{
  "user": {
    "informations:"{
        "name1":"user name1",
        "name2":"user name 2"
    }
  }  
}

And try do add the object like this:

cJSON *root;
cJSON *user;
cJSON *info;

root = cJSON_CreateObject();
cJSON_AddItemToObject(root,"user", user = cJson_CreateObject());
cJSON_AddItemToObject(user,"informations", info = cJson_CreateObject());
cJSON_AddStringToObject(info, "name", name.c_str());
cJSON_AddStringToObject(info, "city", city.c_str());

Its the right way to do this using cJSON? Because its not working and I don't know if the problem is in my C++ or in my Java client that sends the data to my C++ server.


回答1:


Although you did not specify, why your code is not working, this code below, should generate the sample you provided.

#include <iostream>
#include "cJSON.h"

int main() {
  cJSON *root;
  cJSON *user;
  cJSON *info;

  std::string name1 = "user name1";
  std::string name2 = "user name 2";

  root = cJSON_CreateObject();
  cJSON_AddItemToObject(root,"user", user = cJSON_CreateObject());
  cJSON_AddItemToObject(user,"informations", info = cJSON_CreateObject());
  cJSON_AddStringToObject(info, "name1", name1.c_str());
  cJSON_AddStringToObject(info, "name2", name2.c_str());

  std::cout << cJSON_Print(root) << std::endl;
  return 0;
}

The cJSON documentation seems pretty straightforward and your code looks generally fine. There is also a "test.c" file in cJSON sources, where you can find more code samples how to use it.



来源:https://stackoverflow.com/questions/43272300/cjson-c-add-item-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!