0

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.

Sled
  • 18,541
  • 27
  • 119
  • 168
Pik93
  • 49
  • 1
  • 2
  • 12

2 Answers2

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.

pe3k
  • 796
  • 5
  • 15
  • My "informations" object arrive null. Ok your code is the basically the same than my. Ok, so probably the problem is in my client, we dont send the correct data to my c++ server. Thanks ;) – Pik93 Apr 07 '17 at 09:05
0

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)
JK.Tang
  • 11
  • 2