Reputation: 49
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.
Upvotes: 0
Views: 5990
Reputation: 11
This code looks fine. Notice if the CJSON library versions on the client side and the server side are consistent. Changes in the data structure of the old CJSON library and the new CJSON library may cause this problem
old: enter image description here as follows:
#define cJSON_String 4
new: enter image description here as follows:
#define cJSON_String (1 << 4)
Upvotes: 0
Reputation: 804
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.
Upvotes: 1