I'm working on native C++ development and looking for JSON parser that can handle complex JSON files and convert into class objects.
I've looked at native benchmarks for JSON parsers available in C++ and came to conclusion that RapidJSON is popular and best fit considering processing time and size handling.
My requirement is to convert JSON objects to user defined classes and vice versa.
The Jackson has Objectmapper class that provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.
QUESTIONS:
- Is there an equivalent in RapidJSON or other JSON parser that allow us to configure Serialize and Deserialize feature (ex: Jackson JAVA library is the highly customizable serialization and deserialization process, converting JSON objects to Java classes)?
- If No, What's the right way to work around it? Is there only way to build your own serializer to convert to our custom classes?
NOTE: I've looked at few posts on stackoverflow and did not find one that answers it.
I think ThorsSerializer does the job.
All you have to do is declare via
ThorsAnvil_MakeTrait()
what fields in a class are serializable (see below).You can use RapidJSON (or several other libraries) but you need to write customer code to convert from the JSON objects generated by the library into your own objects. This is not terribly hard.
The other disadvantage of most libraries is that they actually build a full representation of the data in JSON like objects and you need to copy the data into your structure. For small objects not a problem but for more complex structures this can take up some space. The ThorsSerializer avoids this completely and copies data directly into your structures: see look at memory used.
Using the same example as @Daniel
Using ThorsSerializer: https://github.com/Loki-Astari/ThorsSerializer
Note: I am the author.
Then reading/writting json in main is simple:
TO build:
Output:
jsoncons, nlohmann and ThorsSerializer all support conversion between JSON and C++ objects. Examples with jsoncons and nlohmann are shown below, Martin York has one for his ThorsSerializer in a separate posting. The latter in my opinion is very nice, and certainly wins the prize for brevity. In the spirit of Oscar Wilde's quote that "imitation is the sincerest form of flattery", I've introduced the macro JSONCONS_MEMBER_TRAITS_DECL to jsoncons, and modified that example accordingly.
Consider
Using jsoncons to convert between
s
and anstd::vector<ns::book>
:Output:
Using nlohmann to convert between
s
and anstd::vector<ns::book>
:Output: