Converting C++ class to JSON

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

    In RareCpp I've created a very effective JSON Library on top of a reflection implementation. It's written for C++17 and works with Visual Studios, g++, and Clang. The library is header only, meaning you need only copy the reflect and json headers into your project to use it.

    The JSON library only requires that you list the fields once in the REFLECT macro; from there it auto identifies appropriate JSON output representations for reading or writing, and can recursively traverse any reflected fields, as well as arrays, STL containers, references, pointers, and more.

    struct MyOtherObject { int myOtherInt; REFLECT(MyOtherObject, myOtherInt) };
    struct MyObject
    {
        int myInt;
        std::string myString;
        MyOtherObject myOtherObject;
        std::vector myIntCollection;
    
        REFLECT(MyObject, myInt, myString, myOtherObject, myIntCollection)
    };
    
    int main()
    {
        MyObject myObject = {};
        std::cout << "Enter MyObject:" << std::endl;
        std::cin >> Json::in(myObject);
        std::cout << std::endl << std::endl << "You entered:" << std::endl;
        std::cout << Json::pretty(myObject);
    }
    

    The above could be ran like so...

    Enter MyObject:
    {
      "myInt": 1337, "myString": "stringy", "myIntCollection": [2,4,6],
      "myOtherObject": {
        "myOtherInt": 9001
      }
    }
    
    
    You entered:
    {
      "myInt": 1337,
      "myString": "stringy",
      "myOtherObject": {
        "myOtherInt": 9001
      },
      "myIntCollection": [ 2, 4, 6 ]
    }
    

    You can also annotate fields to do things like give them a different name in the JSON representation, force them to be strings, and so on.

    struct Point
    {
        NOTE(latitude, Json::Name{"lat"})
        double latitude;
    
        NOTE(longitude, Json::Name{"long"})
        double longitude;
    
        REFLECT(Point, latitude, longitude)
    };
    

    See here for more examples, there are many other features such as capturing super classes, support for reading, traversing, and writing JSON not known at compile time, further customizing JSON representations for specific fields or types, and more.

提交回复
热议问题