本文主要介绍使用 jsoncpp 库,编写C++语言的 JSON 解析程序。
1. 概述
jsoncpp 是一个可以与 JSON 进行交互的C++库。官网定义如下:
jsoncpp is an implementation of a JSON reader and writer in C++.
通过使用 jsoncpp ,我们可以对 JSON 进行读写。
2. 示例代码
2.1 从字符串中解析json
从字符串中解析 json 的代码(jsonstrparse.cpp)如下:
#include <iostream> #include <string> #include <jsoncpp/json/json.h> using namespace std; int main() { string strJsonContent = "{\"role_id\": 1,\"occupation\": \"paladin\",\"camp\": \"alliance\"}"; int nRoleDd = 0; string strOccupation = ""; string strCamp = ""; Json::Reader reader; Json::Value 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++ -o jsonstrparse jsonstrparse.cpp -ljsoncpp
运行编译生成的程序,结果如下:
从上述结果能够看到,我们成功地解析了字符串中的 json 数据。