You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I would like to serialize a field that is std::optional in a way that if its value is std::nullopt then the json for this field will not appear at all.
Here is the example:
#include<iostream>
#include<nlohmann/json.hpp>
#include<optional>using json = nlohmann::json;
usingnamespacenlohmann::literals;
NLOHMANN_JSON_NAMESPACE_BEGIN
template <typename T>
structadl_serializer<std::optional<T>> {
staticvoidto_json(json& j, const std::optional<T>& opt) {
if (opt == std::nullopt) {
j = nullptr; // This will produce "age": null, but I would like to not to serialize that object at all.
} else {
j = *opt; // this will call adl_serializer<T>::to_json which will// find the free function to_json in T's namespace!
}
}
staticvoidfrom_json(const json& j, std::optional<T>& opt) {
if (j.is_null()) {
opt = std::nullopt;
} else {
opt = j.templateget<T>(); // same as above, but with// adl_serializer<T>::from_json
}
}
};
NLOHMANN_JSON_NAMESPACE_END
classperson
{
private:
std::string nameOfPerson = "John Doe";
std::string address = "123 Fake St";
std::optional<int> age = -1;
public:person() = default;
person(std::string name_, std::string address_, std::optional<int> age_)
: nameOfPerson(std::move(name_)), address(std::move(address_)), age(age_)
{}
NLOHMANN_DEFINE_TYPE_INTRUSIVE(person, nameOfPerson, address, age)
};
intmain()
{
person p = {"Ned Flanders", "744 Evergreen Terrace", std::nullopt};
// serialization: person -> json
json j = p;
std::cout << "serialization: " << j << std::endl;
}
This will produce text: serialization: {"address":"744 Evergreen Terrace","age":null,"nameOfPerson":"Ned Flanders"}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hello,
I would like to serialize a field that is std::optional in a way that if its value is std::nullopt then the json for this field will not appear at all.
Here is the example:
This will produce text:
serialization: {"address":"744 Evergreen Terrace","age":null,"nameOfPerson":"Ned Flanders"}
but I would like to have:
serialization: {"address":"744 Evergreen Terrace","nameOfPerson":"Ned Flanders"}
Is this possible to do in automatic way or do I have to write something like:
Thank you for any help.
Beta Was this translation helpful? Give feedback.
All reactions