tgt tgt - 4 months ago 60
JSON Question

Converting C++ class to JSON

I'd like to create a JSON string containing the instance variables of my class.

For example,

class Example {
std::string string;
std::map<std::string, std:string> map;
std::vector<int> vector;
};


would become:

{
"string":"the-string-value",
"map": {
"key1":"val1",
"key2":"val2"
},
"vector":[1,2,3,4]
}


I've looked into several C++ libraries for creating JSON and they all seem incredibly complex. I'd like something similar to Javascript's
JSON.stringify(object)
. In other words just pass a std::map to it and receive a string. The map could contain other maps, vectors, lists, strings, numbers and bools.

What's the nicest way to do this?

Thanks for your help.

Edit

I've looked into the following:

json spirit, jsoncpp, zoolib, JOST, CAJUN, libjson, nosjob, JsonBox, jsonme--

Which I understand I can construct a separate JSON object as in an answer below and convert to JSON I'd like to be able to store my stuff in standard collections and convert.

Edit 2

Okay, scrap the idea of serializing a class since it appears that's impossible with C++'s lack of reflection.

Is there a nice way to convert a std::map containing std:maps, std::vectors, std::lists, numbers, strings, and bools to JSON without having to change datatypes or copying data to a new datatype?

Thanks.

Answer

JSON Spirit would allow you to do it like so:

Object addr_obj;

addr_obj.push_back( Pair( "house_number", 42 ) );
addr_obj.push_back( Pair( "road",         "East Street" ) );
addr_obj.push_back( Pair( "town",         "Newtown" ) );

ofstream os( "address.txt" );
write( addr_obj, os, pretty_print );
os.close();

Output:

{
    "house_number" : 42,
    "road" : "East Street",
    "town" : "Newtown"
}

The json_map_demo.cpp would be a nice place to start, I suppose.

Comments