将 C++ 类转换为 JSON

2021-12-21 00:00:00 json serialization c++

我想创建一个包含我的类的实例变量的 JSON 字符串.

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

例如

class Example {  
    std::string string;  
    std::map<std::string, std:string> map;  
    std::vector<int> vector;  
};

会变成:

{
    "string":"the-string-value",
    "map": {
        "key1":"val1",
        "key2":"val2"
    },
    "vector":[1,2,3,4]
}

我研究了几个用于创建 JSON 的 C++ 库,它们看起来都非常复杂.我想要类似于 Javascript 的 JSON.stringify(object) 的东西.换句话说,只需将 std::map 传递给它并接收一个字符串.地图可以包含其他地图、向量、列表、字符串、数字和布尔值.

I've looked into several C++ libraries for creating JSON and they all seem incredibly complex. I'd like something similar to Javascript's JSON.stringify(object). In other words just pass a std::map to it and receive a string. The map could contain other maps, vectors, lists, strings, numbers and bools.

最好的方法是什么?

感谢您的帮助.

编辑

我研究了以下内容:

json精神、jsoncpp、zoolib、JOST、CAJUN、libjson、nosjob、JsonBox、jsonme--

json spirit, jsoncpp, zoolib, JOST, CAJUN, libjson, nosjob, JsonBox, jsonme--

据我所知,我可以在下面的答案中构建一个单独的 JSON 对象并转换为 JSON 我希望能够将我的东西存储在标准集合中并进行转换.

Which I understand I can construct a separate JSON object as in an answer below and convert to JSON I'd like to be able to store my stuff in standard collections and convert.

编辑 2

好吧,放弃序列化类的想法,因为 C++ 缺乏反射,这似乎是不可能的.

Okay, scrap the idea of serializing a class since it appears that's impossible with C++'s lack of reflection.

是否有一种很好的方法可以将包含 std::maps、std::vectors、std::lists、数字、字符串和 bool 的 std::map 转换为 JSON,而无需更改数据类型或将数据复制到新数据类型?

Is there a nice way to convert a std::map containing std:maps, std::vectors, std::lists, numbers, strings, and bools to JSON without having to change datatypes or copying data to a new datatype?

谢谢.

推荐答案

JSON Spirit 会允许你这样做:

Object addr_obj;

addr_obj.push_back( Pair( "house_number", 42 ) );
addr_obj.push_back( Pair( "road",         "East Street" ) );
addr_obj.push_back( Pair( "town",         "Newtown" ) );

ofstream os( "address.txt" );
os.write( addr_obj, os, pretty_print );
os.close();

输出:

{
    "house_number" : 42,
    "road" : "East Street",
    "town" : "Newtown"
}

json_map_demo.cpp 将是一个不错的地方开始吧,我想.

The json_map_demo.cpp would be a nice place to start, I suppose.

相关文章