Thursday, August 7, 2014

Using Rapidjson in Cocos2D-X: Creating a JSON Document in Code and Serializing it

This is based on Cocos2D-X version 3.2

This import is necessary for creating a JSON document and manipulating it:
#include "external/json/document.h"

These imports are necessary for Serialization:
#include "external/json/writer.h"
#include "external/json/stringbuffer.h"

Example code:
rapidjson::Document jsonDoc; // create the object
jsonDoc.SetObject(); // flag it as an object rather than an array,a necessary step for Serialization

// to set a value (using Cocos2D-X String type in this example here)
String* key = “key”;
String* value = “value”
jsonDoc.AddMember(key->getCString(),value->getCString(),jsonDoc.GetAllocator());

// to Serialize to JSON String
rapidjson::StringBuffer sb;
rapidjson::Writer<rapidjson::StringBuffer> writer(sb);
jsonDoc.Accept(writer);
String* jsonString = String::create(sb.GetString());

References:

No comments:

Post a Comment