nlohmann::basic_json::json_serializer¶
template<typenameT,typenameSFINAE>
usingjson_serializer=JSONSerializer<T,SFINAE>;
Template parameters¶
T- type to convert; will be used in the
to_json/from_jsonfunctions SFINAE- type to add compile type checks via SFINAE; usually
void
Notes¶
Default type¶
The default values for json_serializer is adl_serializer.
Examples¶
Example
The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer.
#include<iostream>
#include<nlohmann/json.hpp>
usingjson=nlohmann::json;
namespacens
{
// a simple struct to model a person (not default constructible)
structperson
{
person(std::stringn,std::stringa,intaa)
:name(std::move(n)),address(std::move(a)),age(aa)
{}
std::stringname;
std::stringaddress;
intage;
};
}// namespace ns
namespacenlohmann
{
template<>
structadl_serializer<ns::person>
{
staticns::personfrom_json(constjson&j)
{
return{j.at("name"),j.at("address"),j.at("age")};
}
// Here's the catch! You must provide a to_json method! Otherwise, you
// will not be able to convert person to json, since you fully
// specialized adl_serializer on that type
staticvoidto_json(json&j,ns::personp)
{
j["name"]=p.name;
j["address"]=p.address;
j["age"]=p.age;
}
};
}// namespace nlohmann
intmain()
{
jsonj;
j["name"]="Ned Flanders";
j["address"]="744 Evergreen Terrace";
j["age"]=60;
autop=j.get<ns::person>();
std::cout<<p.name<<" ("<<p.age<<") lives in "<<p.address<<std::endl;
}
Output:
NedFlanders(60)livesin744EvergreenTerrace
Version history¶
- Since version 2.0.0.