Converting C++ class to JSON

前端 未结 11 963
轮回少年
轮回少年 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条回答
  •  萌比男神i
    2020-12-02 12:35

    I wrote a library which designed to solve your problem. However, it is a very new project, not stable enough. Feel free to take a look, the homepage is here::

    https://github.com/Mizuchi/acml

    In your example, you have to add one line like this:

    ACML_REGISTER(Example, ,(string)(map)(vector));
    

    in order to tell the library which member you want to dump. Since C++ have no reflection. And you must give a way to access the member, either use public member level or use friend class.

    And later you just need to do sth like this:

    string result = acml::json::dumps(any_object);

    would become::

    {
        "string": "the-string-value",
        "map":
        {
            "key1": "val1",
            "key2": "val2"
        },
        "vector":
        {
            "type": "std::vector",
            "size": "4",
            "0": "1",
            "1": "2",
            "2": "3",
            "3": "4"
        }
    }
    

    As you see, JSON array is not implemented yet. And everything becomes string now.

提交回复
热议问题