c++ - Boost Variant: How to model JSON? -
i'm trying parse json string using boost spirit store json object recursive data structures:
value <== [null, bool, long, double, std::string, array, object]; array <== [value, value, value, ...]; object <== ["name1": value, "name2": value, ...]; and here's 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 error:
error c2440: 'initializing' : cannot convert 'std::map<_kty,_ty>' 'jsonvalue' moreover, how safely cast jsonvalue jsonobject? when try doing:
boost::get<jsonobject>(aval) = jsonobject(); this gets run-time exception/fatal failure.
any appreciated.
edit:
following @nicol's advice, came out 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 on jsonobject & jsonarray easy 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 posting benefit this.
you have use recursive wrapper (and shouldn't deriving boost::variant):
struct jsonvalue; typedef boost::variant</*types*/, boost::recursive_wrapper<jsonvalue> > jsondatavalue; struct jsonvalue { jsondatavalue value; }; to make boost.spirit take jsonvalue, need write 1 of fusion adaptor things adapt raw variant type struct.
moreover, how safely cast jsonvalue jsonobject? when try doing:
that's not how variants work. if want set them value, set them other value:
jsonvalue val; val.value = jsonvalue();
Comments
Post a Comment