Boost option: how to simulate JSON?

I am trying to parse a JSON string using a Boost Spirit object, storing a JSON object in recursive data structures:

Value <== [null, bool, long, double, std::string, Array, Object]; Array <== [Value, Value, Value, ...]; Object <== ["name1": Value, "name2": Value, ...]; 

And here is my code:

 #include <map> #include <vector> #include <string> #include <boost/variant.hpp> #include <boost/shared_array.hpp> #include <boost/shared_ptr.hpp> struct JsonNull {}; struct JsonValue; typedef std::map<std::string, JsonValue *> JsonObject; typedef std::vector<JsonValue *> JsonArray; struct JsonValue : boost::variant<JsonNull, bool, long, double, std::string, JsonArray, JsonObject> { }; JsonValue aval = JsonObject(); 

When compiling, I get an error:

 Error C2440: 'initializing' : cannot convert from 'std::map<_Kty,_Ty>' to 'JsonValue' 

Also, how to use JsonValue for JsonObject safely? When I try to do:

 boost::get<JsonObject>(aval) = JsonObject(); 

This gets a runtime exception / fatal failure.

Any help is greatly appreciated.

EDIT:

Following @Nicol's advice, I came out with the following code:

 struct JsonNull {}; struct JsonValue; typedef std::map<std::string, JsonValue *> JsonObject; typedef std::vector<JsonValue *> JsonArray; typedef boost::variant< JsonNull, bool, long, double, std::string, JsonObject, JsonArray, boost::recursive_wrapper<JsonValue> > JsonDataValue; struct JsonValue { JsonDataValue data; }; 

I can work with JsonObject and JsonArray as easily as this:

 JsonValue *pJsonVal = new JsonValue(); boost::get<JsonObject>(pCurrVal->data).insert( std::pair<std::string, JsonValue *>("key", pJsonVal) ); boost::get<JsonArray>(pCurrVal->data).push_back(pJsonVal); 

Just post it so everyone can benefit from it.

+7
source share
1 answer

You must use a recursive shell (and you should not be pulled from boost::variant ):

 struct JsonValue; typedef boost::variant</*types*/, boost::recursive_wrapper<JsonValue> > JsonDataValue; struct JsonValue { JsonDataValue value; }; 

In order for Boost.Spirit to take JsonValue, you will need to write one of these Fusion adapters in order to adapt the type of the raw option to the structure.


Also, how to use JsonValue for JsonObject safely? When I try to do:

This is not how options work. If you want to set them to a value, just set them like any other value:

 JsonValue val; val.value = JsonValue(); 
+8
source

All Articles