安装
sudo apt-get install libjsoncpp-dev
编译
正常的g++编译 需要连接jsoncpp库 -ljsoncpp
例如编译 jsoncpp.cpp
g++ jsoncpp.cpp -o jsoncpp -ljsoncpp
组装
一个复杂的json报文 示例,简单的可以搜寻网上示例
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
using namespace std;
int main()
{
Json::Value root,library;
Json::Value school,grade,myclass;
library["biology"] = "生物";
library["math"] = "数学";
library["chinese"] = "语文";
root["library"] = library;
Json::Value tmp1,tmp2,tmp3;//主要是为了生成没有名字的对象存放在数组
tmp1["sorce"].resize(0);
tmp1["num"] = "56";
tmp1["name"] = "一班";
myclass[0] = tmp1; //数组里面的对象才需要进行引用一个临时的value
tmp2["sorce"].resize(0);
tmp2["num"] = "57";
tmp2["name"] = "二班";
myclass.append(tmp2); // /* laneInfoList[1] = tmp2; */ 等价
tmp3["myclass"] = myclass;
grade.append(tmp3); // /* grade[0] = tmp3; */ 等价
school["grade"] = grade;
school["gym"] = "体育馆";
root["school"] = school;
cout<<root.toStyledString()<<endl;
/* Json::StyledWriter stycle; */
/* cout<<stycle.write(root)<<endl; //等价于上面 */
Json::FastWriter faster;
cout<<faster.write(root)<<endl; //不带格式输出
return 0;
}
键的判断与解析(借用上面json报文直接解析)
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
using namespace std;
int main()
{
Json::Value root,library;
Json::Value school,grade,myclass;
library["biology"] = "生物";
library["math"] = "数学";
library["chinese"] = "语文";
root["library"] = library;
Json::Value tmp1,tmp2,tmp3;//主要是为了生成没有名字的对象存放在数组
tmp1["sorce"].resize(0);
tmp1["num"] = "56";
tmp1["name"] = "一班";
myclass[0] = tmp1; //数组里面的对象才需要进行引用一个临时的value
tmp2["sorce"].resize(0);
tmp2["num"] = "57";
tmp2["name"] = "二班";
myclass.append(tmp2); // /* laneInfoList[1] = tmp2; */ 等价
tmp3["myclass"] = myclass;
grade.append(tmp3); // /* grade[0] = tmp3; */ 等价
school["grade"] = grade;
school["gym"] = "体育馆";
root["school"] = school;
/* cout<<root.toStyledString()<<endl; */
/* Json::StyledWriter stycle; */
/* cout<<stycle.write(root)<<endl; //等价于上面 */
/* Json::FastWriter faster; */
/* cout<<faster.write(root)<<endl; //不带格式输出 */
string jsonBuf = root.toStyledString();
Json::Reader reader;
Json::Value parseRoot;
if(reader.parse(jsonBuf,parseRoot)) {
//一层判断
if(parseRoot.isMember("school")) {
cout<<"school exist"<<endl;
//若school 对应一个value 那么可以直接解析 string school = parseRoot["school"].asSting();即可
//直接演示双层的判断和解析
if(parseRoot["school"].isMember("gym")) {
string gym = parseRoot["school"]["gym"].asString();
cout<<"gym = "<<gym<<endl;
}
//其他类似 此时解析一个最内层的
if(parseRoot["school"]["grade"][0]["myclass"][0].isMember("name")) {
string name = parseRoot["school"]["grade"][0]["myclass"][0]["name"].asString();
cout<<"name = "<<name<<endl;
}
//当然 也可以不用写这么长 中间用一个json::Value 来接收一下
Json::Value parsemyclass;
parsemyclass = parseRoot["school"]["grade"][0]["myclass"];
string name1 = parsemyclass[1]["name"].asString();
cout<<"name1 = "<<name1<<endl;
}
}
return 0;
}