示例代码供您参考,如下:
文件.json
{
"B":"b_val2",
"A":{
"AA":"aa_val1",
"AAA" : "aaa_val2",
"AAAA" : "aaaa_val3"
},
"C":"c_val3",
"D":"d_val4"
}
jsoncpp使用场景如下,对于上面的示例 json 文件。
#include <iostream>
#include "json/json.h"
#include <fstream>
using namespace std;
int main(){
Json::Value root;
Json::Reader reader;
const Json::Value defValue; //used for default reference
std::ifstream ifile("file.json");
bool isJsonOK = ( ifile != NULL && reader.parse(ifile, root) );
if(isJsonOK){
const Json::Value s = root.get("A",defValue);
if(s.isObject()){
Json::Value s2 = s.get("AAA","");
cout << "s2 : " << s2.asString() << endl;
}else{
cout << "value for key \"A\" is not object type !" << endl;
}
}
else
cout << "json not OK !!" << endl;
return 1;
}
输出::
s2:aaa_val2
此外,我已经使用“amalgamate.py”来生成和使用上面示例源的 jsoncpp。