将C ++类转换为JSON [英] Converting C++ class to JSON
问题描述
我想创建一个包含我类的实例变量的JSON字符串。
例如,
class Example {
std :: string string;
std :: map< std :: string,std:string>地图;
std :: vector< int>向量;
};
将成为:
{
string:the-string-value,
map:{
key1:val1,
key2 :val2
},
vector:[1,2,3,4]
}
我已经研究了几个C ++库来创建JSON,他们都看起来非常复杂。我想要类似于JavaScript的 JSON.stringify(object)
。换句话说,只是传递一个std :: map到它并接收一个字符串。地图可以包含其他地图,向量,列表,字符串,数字和布尔。
这是最好的方法是什么?
感谢您的帮助。
编辑 v查看以下内容:
json精神,jsoncpp,zoolib,JOST,CAJUN,libjson,nosjob,JsonBox,jsonme -
我知道我可以在下面的答案中构造一个单独的JSON对象,并转换为JSON我想能够存储我的东西在标准集合和转换。
编辑2
好的,废除了序列化一个类的想法,因为它似乎不可能与C ++缺乏反射。
有一个很好的方法来转换std :: map包含std:maps,std :: vectors,std :: lists,numbers,strings和bools JSON不需要更改数据类型或将数据复制到新数据类型?
谢谢。
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);
write(addr_obj,os,pretty_print);
os.close();
输出:
{
house_number:42,
road:East Street,
town:Newtown
}
json_map_demo.cpp 将是一个很好的开始,我想。
I'd like to create a JSON string containing the instance variables of my class.
For example,
class Example {
std::string string;
std::map<std::string, std:string> map;
std::vector<int> vector;
};
would become:
{
"string":"the-string-value",
"map": {
"key1":"val1",
"key2":"val2"
},
"vector":[1,2,3,4]
}
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.
What's the nicest way to do this?
Thanks for your help.
Edit
I've looked into the following:
json spirit, jsoncpp, zoolib, JOST, CAJUN, libjson, nosjob, JsonBox, jsonme--
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.
Edit 2
Okay, scrap the idea of serializing a class since it appears that's impossible with C++'s lack of reflection.
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?
Thanks.
JSON Spirit would allow you to do it like so:
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" );
write( addr_obj, os, pretty_print );
os.close();
Output:
{
"house_number" : 42,
"road" : "East Street",
"town" : "Newtown"
}
The json_map_demo.cpp would be a nice place to start, I suppose.
这篇关于将C ++类转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!