0

Using libraries like jsoncpp to serialize my C++ objects and data (e.g. to plot them in Python), I really get tired of all the loops in my code to convert std::vector< double >s into Json::Values. I end up re-typing the same lines again and again. Therefore I'd like to make this a little easier.

I have two use cases: Convert STL types (at least std::vector, std::map) from and to Json::Value, and do this with my own data types as well.

Solution for own data types:

  • define constructor expecting const Json::Value&, the constructor then tries to fill the object with data or throws exceptions if the passed value does not meet specific requirements
  • define operator Json::Value() as a member function of my class.

This way, I should be able to write stuff like that:

MyObj o;
Json::Value root;
root["foo"] = o;
MyObj reconstructed(root["foo"]);

But how should I do this with STL types? Write explicit functions, maybe templates, or should I do the same like for my own data types, except that I use free functions instead of member functions? What is the best practice?

wal-o-mat
  • 7,158
  • 7
  • 32
  • 41

1 Answers1

1

You can write a single function to do that, using for_each.

If you want to support nested containers (vector in vector etc), then you need wrapper functions and call the function recursively, until the input type allows straight conversion to a Json::Value.

Domi
  • 22,151
  • 15
  • 92
  • 122
  • Sorry for the confusion, I edited my question: It makes me tired to repeat the same piece of code again and again, so it's desireable to have implicit conversion for me. I know how to convert a vector into a Json::Value in little code, but don't know *where* to put the appropriate code. – wal-o-mat Nov 29 '13 at 08:56
  • Eh... Just put it in a function and put it in utility file that includes Jsoncpp. If I have such utility files that depend on a library, I usually call the file pair: nameofthelib_util .h/cpp or NameofthelibUtil.h/cpp. – Domi Nov 29 '13 at 09:00
  • My question is: Are the functions explicit, like "vec_to_json" or are they implicit, like my `operator` example above ... more a "best practice" than a "I don't know how this works at all". – wal-o-mat Nov 29 '13 at 09:15
  • You cannot add an explicit conversion operator to Json::Value, unless you want to change the class yourself. That is covered [here](http://stackoverflow.com/questions/6120841/is-it-possible-to-write-auto-cast-operator-outside-a-struct). In your case, you can just add a new function that returns a Json::Value object. – Domi Nov 29 '13 at 09:19
  • Thank you, the SO post was exactly my missing link. – wal-o-mat Nov 29 '13 at 09:22