method
json
Objectsj
from the structureperson
subjectp
fetch data, need to implementto_json
the function
void to_json(json& j, const person& p) {
j = json{
{"name", p.name}, {"address", p.address}, {"age", p.age}};
}
- Structure of
person
an objectp
fromjson
the objectj
data fetch, the need to implementfrom_json
function
void from_json(const json& j, person& p) {
j.at("name").get_to(p.name);
j.at("address").get_to(p.address);
j.at("age").get_to(p.age);
}
- usage
json j = p; //调用 to_json
person p = j.get<person>(); //调用from_json
Personal implementation code
struct SubModelData{
std::string module_key_name;
std::string json_type;
std::string default_value;
};
void from_json(const nlohmann::json& j,SubModelData& sub_model_data){
j.at("default_value").get_to(sub_model_data.default_value);
j.at("json_type").get_to(sub_model_data.json_type);
j.at("key_name").get_to(sub_model_data.module_key_name);
}
// 使用
SubModelData sub_model_data = j.get<SubModelData>();
Note:
function from_json
and to_json
as well as the structure declaration should be placed under the same namespace, or will not find the corresponding function implicitly calls
More help documents: https://github.com/nlohmann/json