JSON for Modern C++ realizes the conversion of json object and structure data

method

  • jsonObjects jfrom the structure personsubject pfetch data, need to implement to_jsonthe function
void to_json(json& j, const person& p) {
        j = json{
   
   {"name", p.name}, {"address", p.address}, {"age", p.age}};
    }
  • Structure of personan object pfrom jsonthe object jdata fetch, the need to implement from_jsonfunction
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_jsonand to_jsonas 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

Guess you like

Origin blog.csdn.net/weixin_39139505/article/details/103210458