前言
jsoncpp 库
jsoncpp
是一个可以与JSON
进行交互的C++
库
示例代码
1. 解析 json 对象
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
using namespace std;
int main()
{
// 待解析的 json 字符串
string strJsonContent = "{\"role_id\": 1,\"occupation\": \"paladin\",\"camp\": \"alliance\"}";
// 待解析的结果
int nRoleDd = 0;
string strOccupation = "";
string strCamp = "";
// json 解析器
Json::Reader reader;
// json 根对象
Json::Value root;
// 将 strJsonContent 解析到 root
if (reader.parse(strJsonContent, root))
{
nRoleDd = root["role_id"].asInt();
strOccupation = root["occupation"].asString();
strCamp = root["camp"].asString();
}
cout << "role_id is: " << nRoleDd << endl;
cout << "occupation is: " << strOccupation << endl;
cout << "camp is: " << strCamp << endl;
return 0;
}
编译:g++ jsonstrparse.cpp -o jsonstrparse -ljsoncpp
2. 解析带有数组的 json
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
using namespace std;
/*
{
"list" : [
{
"camp" : "alliance",
"occupation" : "paladin",
"role_id" : 1
},
{
"camp" : "alliance",
"occupation" : "Mage",
"role_id" : 2
}
],
"type" : "roles_msg",
"valid" : true
}
*/
int main()
{
// 待解析的 json 字符串
string strJsonContent = "{\"list\" : [{ \"camp\" : \"alliance\",\"occupation\" : \"paladin\",\"role_id\" : 1}, \
{\"camp\" : \"alliance\",\"occupation\" : \"Mage\",\"role_id\" : 2}],\"type\" : \"roles_msg\",\"valid\" : true}";
// 待解析的结果
string strType;
int nRoleDd = 0;
string strOccupation;
string strCamp;
// 对象
Json::Reader reader;
Json::Value root;
// 解析
if (reader.parse(strJsonContent, root))
{
// 【获取非数组内容】
strType = root["type"].asString();
cout << "type is: " << strType << endl;
// 【获取数组内容】
if (root["list"].isArray())
{
// 数组内有几个对象(size)
int nArraySize = root["list"].size();
for (int i = 0; i < nArraySize; i++)
{
nRoleDd = root[