tgt tgt - 1 year ago 383
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:

"map": {

I've looked into several C++ libraries for creating JSON and they all seem incredibly complex. I'd like something similar to Javascript's
. 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.


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?


Answer Source

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 );


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download