Converting C++ class to JSON

前端 未结 11 948
轮回少年
轮回少年 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:32

    Any good C++ JSON library should do this and it is sad to see that they don't -- with the exception of ThorsSerializer and apparently Nosjob as mentioned in this question.

    Of course, C++ does not have reflection like Java, so you have to explicitly annotate your types:
    (copied from the ThorsSerializer documentation)

    #include "ThorSerialize/JsonThor.h"
    #include "ThorSerialize/SerUtil.h"
    #include 
    #include 
    #include 
    #include 
    
    class Example {
        std::string string;
        std::map map;
        std::vector vector;
    
        // Allow access to the class by the serialization library.
        friend class ThorsAnvil::Serialize::Traits;
    
        public:
            Example(std::string const& s, std::map const& m, std::vector const& v)
                : string(s), map(m), vector(v)
            {}
    };
    
    // Define what members need to be serilizable
    ThorsAnvil_MakeTrait(Example, string, map, vector);
    

    Example Usage:

    int main()
    {
        using ThorsAnvil::Serialize::jsonExport;
        using ThorsAnvil::Serialize::jsonImport;
    
    
        Example     e1 {"Some Text", {{"ace", "the best"}, {"king", "second best"}}, {1 ,2 ,3, 4}};
    
        // Simply serialize object to json using a stream.
        std::cout << jsonExport(e1) << "\n";
    
        // Deserialize json text from a stream into object.
        std::cin  >> jsonImport(e1);
    }
    

    Running:

    {
        "string": "Some Text",
        "map":
        {
            "ace": "the best",
            "king": "second best"
        },
        "vector": [ 1, 2, 3, 4]
    }
    

    You cannot do better than this in C++.

提交回复
热议问题