1、cmake安装
git clone https://github.com/open-source-parsers/jsoncpp.git cd jsoncpp mkdir -p build cd build cmake -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=OFF -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" .. make sudo make install
2、使用
添加头文件json.h
#include <./jsoncpp/include/json/json.h>b
编译时使用动态库,添加
g++ -ljsoncpp
3、示例代码
3.1 从文件/字符串读入json数据
alice.cpp
#include <iostream> #include <fstream> #include <string> #include </home/clay/jsoncpp/include/json/json.h> using namespace std; int main() { ifstream ifs("alice.json"); Json::Reader reader; Json::Value obj; reader.parse(ifs, obj); // reader can also read strings cout << "Book: " << obj["book"].asString() << endl; cout << "Year: " << obj["year"].asUInt() << endl; const Json::Value& characters = obj["characters"]; // array of characters for (int i = 0; i < characters.size(); i++){ cout << " name: " << characters[i]["name"].asString(); cout << " chapter: " << characters[i]["chapter"].asUInt(); cout << endl; } //read from string string alice_json=R"({"Age":22,"Name":"Clay"})"; Json::Reader re_ali; Json::Value ob_ali; re_ali.parse(alice_json,ob_ali); cout<<"Age="<<ob_ali["Age"].asInt()<<endl; cout<<"Name="<<ob_ali["Name"].asString()<<endl; return 0; }
alice.json文件
{ "book":"Alice in Wonderland", "year":1865, "characters": [ {"name":"Jabberwock", "chapter":1}, {"name":"Cheshire Cat", "chapter":6}, {"name":"Mad Hatter", "chapter":7} ] }
3.2 向文件/字符串读入json数据
writedemo.cpp
#include <iostream> #include <fstream> #include </home/clay/jsoncpp/include/json/json.h> using namespace std; int main() { //根节点 Json::Value root; //根节点属性 root["name"] = Json::Value("shuiyixin"); root["age"] = Json::Value(21); root["sex"] = Json::Value("man"); //子节点 Json::Value friends; //子节点属性 friends["friend_name"] = Json::Value("ZhaoWuxian"); friends["friend_age"] = Json::Value(21); friends["friend_sex"] = Json::Value("man"); //子节点挂到根节点上 root["friends"] = Json::Value(friends); //数组形式 root["hobby"].append("sing"); root["hobby"].append("run"); root["hobby"].append("Tai Chi"); //直接输出 cout << "FastWriter:" << endl; Json::FastWriter fw; cout << fw.write(root) << endl << endl; //缩进输出 cout << "StyledWriter:" << endl; Json::StyledWriter sw; cout << sw.write(root) << endl << endl; //输出到字符串 string jsonstr = sw.write(root); cout << jsonstr << endl; //输出到文件 ofstream os; os.open("demo.json"); if (!os.is_open()) cout << "error:can not find or create the file which named \" demo.json\"." << endl; os << sw.write(root); os.close(); return 0; }
Reference:
https://www.cnblogs.com/__tudou__/p/14957646.html;
https://en.wikibooks.org/wiki/JsonCpp#Example;
https://github.com/open-source-parsers/jsoncpp;
https://blog.csdn.net/shuiyixin/article/details/89330529。
本文来自博客园,作者:Clay,转载请注明原文链接:https://www.cnblogs.com/clayyjh/p/16332433.html