Featured image of post Useful C++ libraries #01 nlohmann:json

Useful C++ libraries #01 nlohmann:json

Table of contents

https://github.com/nlohmann/json

A very nice library for working with Json. It gives us support for this format in several ways, but I would like to present one that I use. Unfortunately, this way works only for our types, which we can edit. As a result, I have doubts about maintaining the Single Responsibility Principle. But don’t forget that this library also has solutions for (de-)serialization of third party types that we cannot modify.

Why I like this library.

  • It is available as a single-file header, which makes it easy to include in a project.

  • Very comprehensive and decent documentation that makes it easy to learn about the available functionality and how to use it yourself.

Example of using Nlohmann::json
struct MyDataType {
    std::string someStrValue;
    double someDoubleValue;
    int someIntValue;

    // Adding (de-) serialization (1)
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(MyDataType, someStrValue, someDoubleValue, someIntValue)
};

///
/// Function representing how to turn JSON into our own type
///
MyDataType toMyDataType(const std::string& rawJson) {
    auto j = nlohmann::json::parse(rawJson); (2)
    auto myDataType = j.get<MyDataType>();
    return myDataType;
}

///
/// Function representing how to turn our own type into JSON.
///
std::string toString(const MyDataType& data) {
    nlohman::json jsonData = data; // This is where the automatic conversion takes place (3)
    return jsonData.dump();
}
1 First, we need to add a macro that includes serializing and deserializing functions.
2 Then we can already perform JSON deserialization (as a string) to an object,
3 and serialization from the object to JSON.
comments powered by Disqus
Please keep in mind that the blog is in preview form at this point and may contain many errors (but not merit errors!). Nevertheless, I hope you enjoy the blog! Many illustrations appeared on the blog thanks to unsplash.com!
Built with Hugo
Theme Stack designed by Jimmy