PDA

View Full Version : JSON?



RandomClown
09-01-2014, 05:21 AM
I see that there is JSON stuff (http://clanlib.org/documentation/3.0/classclan_1_1JsonValue.html#a47af70f4435c13218b1c9 afbdadb2e65ab239dc16083d2b3d738fcc4674530f84) in ClanLib, but I cant figure out how to use it. I dont see any samples for it.

I tried a bunch of things like initializing an object JsonValue val("{\"proc\":42}"), but nothing I do seems to make sense.

How do I start using it? I need to store a bunch of wstring pairs.


// Sample data
[
{
"name": "朱聖硯",
"anotherkey": "abc"
},
{
"name": "John",
"anotherkey": "42"
},
]

Judas
09-01-2014, 01:08 PM
Imagine a data.json file with the following content:



{
"text": "foobarism",
"life": 42
}


The syntax is as follows:



JsonValue value = JsonValue::from_json(File::read_text("data.json"));

std::string text = value["text"];
int life = value["life"];

value["text"] = text + " on and on!";
value["life"] = life * 2;

File::write_text("data2.json", value.to_json());


The code outputs a new data2.json file with:



{
"text": "foobarism on and on!",
"life": 84
}


Note that the JsonValue class got a few outstanding issues:


Some of the operator= functions are missing the C++11 explicit keyword to prevent 'int' and 'bool' matching 'std::string'
Same thing for operator bool() const and operator int() const
JsonValue::read_string does not support unicode escapes yet. You will probably have to fix this if you want to use this class for anything serious.
JsonValue::write_string does not escape strings yet. This also has to be fixed.


Unless someone volunteers to fix these 4 issues I can't really recommend using the JsonValue class at this time.