4

I am trying to create a json document using rapidjson but I don't know how I can replicate part of the following document, in particular the nested object starting with "allocations", for the others elements I do

Value valObjectString(kStringType);
valObjectString.SetString("string");
doc.AddMember("string", valObjectString, doc.GetAllocator());

But what about "allocation" and "url" ?

{
  "string1": "string",
  "string2": "string",
  "string3": "string",
  "string4": "string",
  "string5": "string",
  "allocations": [
    {
      "allocation": "string",
      "url": "string"
    }
  ]
}
Antwane
  • 20,760
  • 7
  • 51
  • 84
user1583007
  • 399
  • 1
  • 5
  • 17

3 Answers3

7

you can do like this

Value valObjectString(kStringType);
valObjectString.SetString("string");
doc.AddMember("string", valObjectString, doc.GetAllocator());

Value array(kArrayType);
Value tmp;
tmp.SetObject();
tmp.AddMember("allocation", "string", doc.GetAllocator());
tmp.AddMember("url", "string", doc.GetAllocator());
array.PushBack(tmp, doc.GetAllocator());
doc.AddMember("allocations", array, doc.GetAllocator());
mkm
  • 673
  • 5
  • 21
ypengju
  • 71
  • 1
  • 3
2

An easy way to create the wanted JSON Document would be to use the "rapidjson/writer.h" include.

You need to use writer.Key() to create the key of the object and name it. Then, you can use writer.String() to set the value of the key.

(Here I used .String(), but you can use any type that is supported by RapidJson.)

Also, you can easily tell the writer when to Start and End objects and arrays with writer.StartObject(), writer.StartArray(), writer.EndObject() and writer.EndArray() commands.

Document yourJsonDoc;

StringBuffer s;
Writer<StringBuffer> writer(s);

writer.StartObject();
writer.Key("string1");
writer.String("string");
writer.Key("string2");
writer.String("string");
writer.Key("string3");
writer.String("string");
writer.Key("string4");
writer.String("string");
writer.Key("string5");
writer.String("string");
writer.Key("allocations");
writer.StartArray();
writer.StartObject();
writer.Key("allocations");
writer.String("string");
writer.Key("url");
writer.String("string");
writer.EndObject();
writer.EndArray();
writer.EndObject();

yourJsonDoc.Parse(s.GetString().c_str());

And so on if you'd like to add additional objects.

Jacobb
  • 41
  • 5
0

Ok you need to create an array containing allocation and url and you need to put this array inside allocations :

rapidjson::Value myArray(rapidjson::kArrayType);

doc.AddMember("allocations", myArray, doc.getAllocator);
Daniel Ryan
  • 6,976
  • 5
  • 45
  • 62
user1583007
  • 399
  • 1
  • 5
  • 17