JSON parsing on Cocos2D-X projects

Jesus Bosch wrote:

arrrg russian is too hard for me… :-S if you write in English (even with bad english like mine) you will have more visits :wink:

Ok, i rewrite my articles to English, but it will be bad English :slight_smile:

not worst than mine :slight_smile:

Anyway, there are few tutorials about cocos2dx out there, so more the better :slight_smile: If they are in English remember you can also link your blog in the Wiki.

Alex, Jesus thanks for a good discussion.
I work with JSON in other way, I took patterns from CCNetwork extension, which you can find here: https://github.com/jandujar/cocos2d-x-extensions/tree/master/extensions/CCNetwork
I’m not sure that my way is better then your one, but sure you can use it for new ideas.

P.S. Alex, I can review your English translation if you wish. Any help? Welcome!

I have issue in traversing the json response parsed by rapid json: I followed the following post:

http://www.jesusbosch.com/2012/08/parsing-json-from-c-and-maybe-from.html

for traversing an array dynamically through loop. I want to traverse the whole dictionary in a loop without knowing its keys. Following is the sample json:

{
key {
type: “soil”,
map_object: true
},
someOtherKey {
type: “soil”,
map_object: true
},
w {
type: “soil”,
map_object: true,
},
2 {
type: “soil”,
map_object: true
}
}
Looking forward for you response. Thanking you in advance. :slight_smile:

You can use jsoncpp…
It’s really easy to use.

I am having a problem getting rapidjson to work. I have reviewed the hints in this thread, as well as this post: http://www.jesusbosch.com/2012/08/parsing-json-from-c-and-maybe-from.html

I have the rapidjson files in the /lib/rapidjson group.
When I try to do the following:

Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator. document.Parse<0>(json).HasParseError();

I get a compilation error:
No matching member function for call to 'Parse'

The odd thing is that I can click into Parse and Xcode will find it in the rapidjson code. But it still refuses to compile.

Anyone have an idea as to what I’m doing wrong? It seems like a simple issue since everyone else in this thread seems to be able to compile.

Thanks in advance!

*[Edit: Please disregard this question. It was a problem with my json variable.]*

Hi, I am trying to iterate Name-Value pair objects in my JSON using rapidJSON, however, the compiler at XCode kept giving me an undeclared identifier for MemberIterator. Anyone has any idea? Thanks.

my json sample would be: {test

Here’s the code:

#include “document.h” //I have done a few settings in my Xcode so that instead of “rapidjson/document.h”, i just need “document.h”
>
using namespace rapidjson;
>
void StartScreen::testURLCallback(CCNode* node, void* data)
{
CCHttpResponse* response = (CCHttpResponse*)(data);
if (response)
{
ostringstream oss;
for (int i = 0; i < response->getResponseData()->size(); i**) {
oss << response->getResponseData->at;
}
CCLOG (oss.str().c_str);
Document d;
d.Parse<0>.c_str);
CCLOG (d[“test”].GetString());
for ; m != d.MemberEnd; m**) //<— this part got compilation error
{
//do something
}
}
}

Ok, I have solved my own problem.

Apparently, it should be:
for (Value::MemberIterator itr = d.MemberBegin()……)

Because the string is not null terminated the garbage in memory after the data loaded is added to the string until it finds a 0 in memory.

This gives you a terminated string…

    std::string fullPath = CCFileUtils::fullPathFromRelativePath("figures.json");
    std::string json = CCFileUtils::getStringFromFile(fullPath);
    document.Parse<0>(json.c_str());
1 Like

plz tell m how we can JSON parsing in cocos2d-x 3.0 .
how we can get value from JSON file.

1 Like

if anyone know about this than rply m fast

Try using rapidjson, it’s included in cocos2d, this link for example rapidjson

Rapidjson is excellent for the absolute best performance, but otherwise I highly recommend nlohman’s json lib since it’s very modern (C+11+), super simple to use, and a single header file to integrate.

#include “HelloWorldScene.h”
#include “SimpleAudioEngine.h”
#include “cocos2d.h”
#include “cocos-ext.h”
#include “json/reader.h”
#include “json/writer.h”
#include “json/document.h”
#include “json/stringbuffer.h”
#include

USING_NS_CC;
USING_NS_CC_EXT;

using namespace std;
using namespace rapidjson;
USING_NS_CC;

Scene* HelloWorld::createScene()
{
return HelloWorld::create();
}

// on “init” you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Scene::init() )
{
return false;
}

rapidjson::Document document;
std::string data = "Levels.json";            //  pass your json file here
std::string content = FileUtils::getInstance()->getStringFromFile(data.c_str());
log("file content: %s", content.c_str());
document.Parse<0>(content.c_str());

if(document.IsObject()){
//change hasmember line levels according to yours root element name
if(document.HasMember(“LEVELS”)){

        const rapidjson::Value& employeeArray = document["LEVELS"];  // you are missing this
        assert(employeeArray.IsArray());
        for (rapidjson::SizeType i = 0; i < employeeArray.Size(); i++)
        {
            const rapidjson::Value & atomicObject  = employeeArray[i];
            std::string firstName;
            std::string lastName;
            if(atomicObject.HasMember("NAME")){
                const rapidjson::Value & name  = atomicObject["NAME"];
                firstName = cocos2d::Value(name.GetString()).asString();
                
            }
            
            if(atomicObject.HasMember("NAME")){
                const rapidjson::Value & name  = atomicObject["NAME"];
                lastName = cocos2d::Value(name.GetString()).asString();
                
            }
            
            
            
            log("Full Name is :---  %s %s",firstName.c_str(), lastName.c_str());
            
        }
    }

}
return true;
}

JSON FILE ==> Levels.json

{
“LEVELS”: [
{
“ID”: 0,
“LOCK”: false,
“NAME”: “LEVEL0”,
“SCORE”: 100,
“SPEED”: 10
},
{
“ID”: 1,
“LOCK”: true,
“NAME”: “LEVEL1”,
“SCORE”: 100,
“SPEED”: 10
},
{
“ID”: 2,
“LOCK”: true,
“NAME”: “LEVEL2”,
“SCORE”: 100,
“SPEED”: 10
},
{
“ID”: 3,
“LOCK”: true,
“NAME”: “LEVEL3”,
“SCORE”: 100,
“SPEED”: 10
},
{
“ID”: 4,
“LOCK”: true,
“NAME”: “LEVEL4”,
“SCORE”: 100,
“SPEED”: 10
}
]
}

1 Like