C++ 用C+处理JSON信息+;还有rapidjson
我有一个JSON:C++ 用C+处理JSON信息+;还有rapidjson,c++,json,rapidjson,C++,Json,Rapidjson,我有一个JSON: [{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 183.26, "Year": 2002 }, {repeated struct across 3mb .json}] 我想将“Country”值存储到std::vector countries中但我不知道怎么做(我想计算一下JSON中有多少不同的国家
[{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 183.26, "Year": 2002 }, {repeated struct across 3mb .json}]
我想将“Country”值存储到std::vector countries中代码>但我不知道怎么做(我想计算一下JSON中有多少不同的国家)。到目前为止,我已经做了以下工作:
std::ifstream ifs("../data/data.json");
if (!ifs.is_open()) {
std::cerr << "Could not open file for reading!\n";
return EXIT_FAILURE;
}
IStreamWrapper isw(ifs);
Document doc;
doc.ParseStream(isw);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
doc.Accept(writer);
if (doc.HasParseError()){
std::cout << "Error : " << doc.GetParseError() << '\n' << "Offset : " <<
doc.GetErrorOffset() << '\n';
return EXIT_FAILURE;
}
关于如何迭代的示例(json值是数组,对象具有迭代器)
constepr std::string_view stringJson=R“([{“k1”:“v1”、“k2”:“v2”},{“k1”:“v1”、“k2”:“v2”}]);
rapidjson::DocumentDocumentJSON;//创建根rapidjson对象
documentJson.Parse(stringJson.data());
如果(documentJson.IsArray()==true)//是,我们知道它是一个数组:)
{
for(const auto&itArray:documentJson.GetArray())//迭代数组
{
if(itArray.IsObject()==true)//它们都是对象
{
for(const auto&itObject:itArray.GetObject())
{
const auto&_name=itObject.name;//获取名称
const auto&_value=itObject.value;//获取值
STD:在你学习如何从JSON中提取值时,如果你发现一个更具体的问题或者更具体的疑问,那么它会更容易帮助你。考虑使用和从源代码中获取灵感。如果有兴趣,请给我发一封电子邮件给<代码>。basile@starynkevitch.net
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 183.26, "Year": 2002 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 198.736, "Year": 2003 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 200.069, "Year": 2004 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 223.737, "Year": 2005 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 235.731, "Year": 2006 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 267.177, "Year": 2007 }...
constexpr std::string_view stringJson = R"([ {"k1": "v1", "k2": "v2"}, {"k1": "v1", "k2": "v2"} ])";
rapidjson::Document documentJson; // Create root rapidjson object
documentJson.Parse( stringJson.data() );
if( documentJson.IsArray() == true ) // Yes, we know it is an array :)
{
for( const auto& itArray : documentJson.GetArray() ) // iterate array
{
if( itArray.IsObject() == true ) // They are all objects
{
for( const auto& itObject : itArray.GetObject() )
{
const auto& _name = itObject.name; // get name
const auto& _value = itObject.value; // get value
std::cout << _name.GetString() << " : " << _value.GetString() << "\n";// dump it
}
}
}
}