I need to read a file .json where I have the information from the levels of my game, I’m using the library rapidjson, but i can’t find how to read or modify the file.
Can someone help me out ?
I am currently using rapidJSON to parse JSON data to __Dictionary
. This is roughly how I do it:
__Dictionary* getDictionaryFromJSON(string json)
{
Document d;
d.Parse<0>(json.c_str());
if (d.HasParseError())
{
return NULL;
}
if (d.GetType() != kObjectType)
{
return NULL;
}
__Dictionary* dict = __Dictionary::create();
for (rapidjson::Value::MemberIterator itr = d.MemberBegin(); itr != d.MemberEnd(); itr++)
{
string key = itr->name.GetString();
Ref* obj = parseValue(itr->value);
if(obj)
{
dict->setObject(obj, key);
}
}
return dict;
}
Ref* parsePrimitiveTypeFromValue(rapidjson::Value& v)
{
ostringstream oss;
if (v.IsNumber())
{
if (v.IsInt())
{
oss << v.GetInt();
}
else if (v.IsInt64())
{
oss << v.GetInt64();
}
else if (v.IsDouble())
{
oss << (int)v.GetDouble();
}
return __String::create(oss.str().c_str());
}
else
{
if (v.IsString())
{
return __String::create(v.GetString());
}
else
{
if (v.IsTrue() || v.IsFalse())
{
oss << v.GetBool();
return __String::create(oss.str());
}
}
}
return NULL;
}
Ref* parseObjectTypeFromValue(rapidjson::Value& v)
{
__Dictionary* dict = __Dictionary::create();
for (rapidjson::Value::MemberIterator itr = v.MemberBegin(); itr != v.MemberEnd(); itr++)
{
string key = itr->name.GetString();
Ref* obj = parseValue(itr->value);
if (obj)
{
dict->setObject(obj, key);
}
}
return dict;
}
Ref* parseArrayTypeFromValue(rapidjson::Value& v)
{
__Array* array = __Array::create();
for (rapidjson::Value::ValueIterator itr = v.Begin(); itr != v.End(); itr++)
{
Ref* obj = parseValue(*itr);
if (obj)
{
array->addObject(obj);
}
}
return array;
}
Ref* parseValue(rapidjson::Value& v)
{
switch (v.GetType()) {
case kObjectType:
return parseObjectTypeFromValue(v);
break;
case kArrayType:
return parseArrayTypeFromValue(v);
break;
case kNumberType:
case kStringType:
case kTrueType:
case kFalseType:
{
return parsePrimitiveTypeFromValue(v);
}
break;
default:
return NULL;
break;
}
return NULL;
}
Hope it helps.
And if you’re looking for a JSON -> ValueMap using rapidjson: