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 be
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)?
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).
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?
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.
#include
const std::string s = R"(
[
{
"author" : "Haruki Murakami",
"title" : "Kafka on the Shore",
"price" : 25.17
},
{
"author" : "Charles Bukowski",
"title" : "Pulp",
"price" : 22.48
}
]
)";
namespace ns {
struct book
{
std::string author;
std::string title;
double price;
};
} // namespace ns
#include
#include "ThorSerialize/Traits.h" // for ThorsAnvil_MakeTrait
#include "ThorSerialize/SerUtil.h" // Has definitions for all STL types.
#include "ThorSerialize/JsonThor.h" // JSON version: There is also YAML
ThorsAnvil_MakeTrait(ns::book, author, title, price);
Then reading/writting json in main is simple:
int main()
{
using ThorsAnvil::Serialize::jsonExport;
using ThorsAnvil::Serialize::jsonImport;
std::stringstream stream(s);
ns::book book;
std::vector allBooks;
stream >> jsonImport(allBooks);
std::cout << jsonExport(allBooks)
<< "\n\n"
<< jsonExport(allBooks, ThorsAnvil::Serialize::PrinterInterface::OutputType::Stream)
<< "\n\n";
}
TO build:
> g++ -std=c++14 main.cpp -lThorSerialize17
Output:
> ./a.out
[
{
"author": "Haruki Murakami",
"title": "Kafka on the Shore",
"price": 25.17
},
{
"author": "Charles Bukowski",
"title": "Pulp",
"price": 22.48
}]
[{"author":"Haruki Murakami","title":"Kafka on the Shore","price":25.17},{"author":"Charles Bukowski","title":"Pulp","price":22.48}]