cJSON c ++-添加项目对象 [英] cJSON c++ - add item object
问题描述
我正在使用 cJSON库.对于这样的带有JSON的正文示例请求:
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());
但是现在我的body json有点不同:
But now i have a body json little different:
{
"user": {
"informations:"{
"name1":"user name1",
"name2":"user name 2"
}
}
}
并尝试添加如下对象:
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());
使用cJSON做到这一点的正确方法吗?因为它不起作用,而且我不知道问题出在我的C ++还是将数据发送到我的C ++服务器的Java客户端中.
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.
推荐答案
尽管您未指定,但代码为何不起作用,下面的代码应生成您提供的示例.
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;
}
cJSON文档似乎非常简单,您的代码通常看起来还不错. cJSON源代码中还有一个"test.c"文件,您可以在其中找到更多使用示例的代码示例.
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.
这篇关于cJSON c ++-添加项目对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!