0

I want to create a json object in cocos2d-x 3.4 with rapidjson and convert it to a string:

rapidjson::Document doc;
doc.SetObject();
doc.AddMember("key1",1,doc.GetAllocator());
doc["key2"]=2;

rapidjson::StringBuffer sb;
rapidjson::Writer<rapidjson::StringBuffer> writer(sb);
doc.Accept(writer);

CCLOG("%s",sb.GetString());

but the output is {"key1":1} not {"key1":1,"key2":2}, why?

Wesley
  • 4,084
  • 6
  • 37
  • 60
ggrr
  • 7,737
  • 5
  • 31
  • 53

1 Answers1

0

In old (0.1x) versions of RapidJSON, doc["key2"] returns a Value singleton representing Null. doc["key2"] = 2 actually writes to that singleton.

In newer versions of RapidJSON (v1.0.x), this behavior has been changed. It basically make assertion fail for a key that is not found in a JSON object, in order to solve exact problem you mentioned.

As a reminder, when an operation potentially requires allocating memory (such as AddMember or PushBack, an Allocator object must be appeared. Since operator[] normally only has one parameter, it cannot add new members as in STL. This is quite weird and not very user-friendly, but this is a tradeoff in RapidJSON's design for performance and memory overheads.

Milo Yip
  • 4,902
  • 2
  • 25
  • 27