Converting C++ class to JSON

前端 未结 11 984
轮回少年
轮回少年 2020-12-02 11:56

I\'d like to create a JSON string containing the instance variables of my class.

For example,

class Example {  
    std::string string;  
    std::ma         


        
11条回答
  •  天涯浪人
    2020-12-02 12:35

    nlohmann::json allows you to have arbitrary type conversions. It's described here https://nlohmann.github.io/json/features/arbitrary_types/ in more detail.

    class Example {  
        std::string string;  
        std::map map;  
        std::vector vector;
    
        // Add this to your code.
        NLOHMANN_DEFINE_TYPE_INTRUSIVE(Example, string, map, vector);
    };
    

    Since the class members are private you can use the macro: NLOHMANN_DEFINE_TYPE_INTRUSIVE(...). I don't know whether it works with std::map or std::vector but it works with primitive types.

    Like here:

    struct MyStruct {
        std::string name;
        int number;
    
        NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(MyStruct, name, number);
    };
    

    Note how I used NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE because the struct members are public.

    Now I can call the to_json(Json& j, const MyStruct& s) function like:

    MyStruct s;
    s.name = "test";
    s.number = 11;
    
    nlohmann::json j;
    s.to_json(j, s);
    std::cout << j << std::endl;
    // {"name":"test","number":11}
    

提交回复
热议问题