Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 716
tgt Avatar asked Nov 21 '11 23:11

tgt


People also ask

Can we convert string to JSON in C?

Using JsonConverterJsonConvert class has a method to convert to and from JSON string, SerializeObject() and DeserializeObject() respectively. It can be used where we won't to convert to and from a JSON string.

Does C# support JSON?

Json can use the C# source generation feature to improve performance, reduce private memory usage, and facilitate assembly trimming, which reduces app size. For more information, see How to choose reflection or source generation in System. Text. Json.

What is JsonConvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

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" ); os.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.

like image 175
sehe Avatar answered Sep 20 '22 16:09

sehe