一、基本概念
1、JSON是一种轻量级数据交换格式。它被设计成易于人阅读和编写,并易于机器解析和生成。JSON是基于JavaScript语法的一个子集。
2、JSON中的数据类型包括:number, string, boolean, object, array, null。
3、C++解析JSON的库很多,常用的有RapidJSON、boost.property_tree、nlohmann/json等等。
二、RapidJSON库解析JSON
RapidJSON是C++的一种JSON解析库,由于它的解析速度非常快,并且它提供了灵活的API,越来越多的人开始使用它。以下是一个使用RapidJSON解析JSON的例子:
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include
using namespace rapidjson;
using namespace std;
int main() {
const char* json = "{\"name\":\"Jack\\\",\\\"age\\\":27}";
Document document;
document.Parse(json);
Value& name = document[\"name\"];
Value& age = document[\"age\"];
cout << \"name:\" << name.GetString() << endl;
cout << \"age:\" << age.GetInt() << endl;
return 0;
}
三、boost.property_tree库解析JSON
boost库是C++程序员必备的一个库,boost.property_tree库是boost库中的一个JSON解析库。以下是一个使用boost.property_tree解析JSON的例子:
#include
#include
#include
using namespace std;
using boost::property_tree::ptree;
int main() {
std::string jsonStr = \"{ \\\"name\\\" : \\\"Jack\\\", \\\"age\\\" : 27 }\";
stringstream ss(jsonStr);
ptree pt;
read_json(ss, pt);
string name = pt.get(\"name\");
int age = pt.get(\"age\");
cout << \"name:\" << name << endl;
cout << \"age:\" << age << endl;
return 0;
}
四、nlohmann/json库解析JSON
nlohmann/json是一个面向现代C++的JSON解析和生成库。使用nlohmann/json解析JSON非常简单,只需要包含一个头文件即可。以下是一个使用nlohmann/json解析JSON的例子:
#include
#include
using namespace std;
using json = nlohmann::json;
int main() {
string jstr = R\"({"name":"Jack","age":27})\";
auto j = json::parse(jstr);
string name = j[\"name\"];
int age = j[\"age\"];
cout << \"name:\" << name << endl;
cout << \"age:\" << age << endl;
return 0;
}
五、解析JSON中的数组
在JSON中,数组是一系列值,用方括号表示,值之间用逗号隔开。C++解析JSON中的数组需要使用循环进行操作,以下是一个使用nlohmann/json解析JSON中数组的例子:
#include
#include
using namespace std;
using json = nlohmann::json;
int main() {
string jstr = R\"({\"data\":[{\"name\":\"Jack\",\"age\":27},{\"name\":\"Lucy\",\"age\":25}]})\";
auto j = json::parse(jstr);
auto data = j[\"data\"];
for (auto& item : data) {
string name = item[\"name\"];
int age = item[\"age\"];
cout << \"name:\" << name << \" age:\" << age << endl;
}
return 0;
}
六、异常处理
在解析JSON的过程中,可能会出现各种各样的异常,例如JSON格式错误、缺少必要的键等等。为了避免程序出现异常或崩溃,我们需要对JSON解析器进行异常处理。以下是一个使用try-catch进行异常处理的例子:
#include
#include
#include
using namespace std;
using json = nlohmann::json;
int main() {
string jStr = R\"({\"name\":\"Jack\",\"age\":27})\";
try {
auto j = json::parse(jStr);
string name = j.at(\"name\");
int age = j.at(\"age\");
cout << \"name:\" << name << \" age:\" << age << endl;
} catch (exception& e) {
cerr << e.what() << endl;
}
return 0;
}
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/193146.html
微信扫一扫
支付宝扫一扫