GameCorder.net

このエントリーをはてなブックマークに追加

Parse json using RapidJson in cocos2dx

parse json response using RapidJson.
RapidJson is a tool to parse json object.
cocos2dx have RapidJson in external folder.
So we can use not download outside.

Parse simple json data

Parse simple json data like...


{
	"name":"jiji,
	"rank":"1"
}
		

Data hava name and rank
Let's parse with rapid json


#include "external/json/document.h"
// Need Document object
rapidjson::Document jsonDoc;
// data is like string above
jsonDoc.Parse(data.c_str());
// parse name
name = jsonDoc["name"].GetString();
// parse rank
rank = jsonDoc["rank"].GetString();
		

Parse array json data

Next parse array json data like...


{
		ranking: [
			{
			name: ""jiji",
			best_time: "0"
			},
			{
			name: "noname",
			best_time: "3.499651"
			}
		]
}
		

In this example have ranking with array.
Let's parse array.


// parse
rapidjson::Document jsonDoc;
// in this case response is api response ofcourse above data
jsonDoc.Parse(response.c_str());
const rapidjson::Value& ranking = jsonDoc["ranking"];
for (int i = 0; i < ranking.Size(); ++i) {
    // name
    name = setString(ranking[i]["name"].GetString());
    // best_time
    bestTime = ranking[i]["best_time"].GetString()
}
		

To parse ranking json data
I use index.

This is available in cocos2dx 3.15.1