这里使用的json解析工具为JSON for Modern C++,使用的话仅需要包含头文件。
获取方式:wget https://github.com/nlohmann/json/releases/download/v3.7.3/json.hpp
JSON
json的序列化功能和map一样,用关联数组的"[]"来任意添加数据,不需要指定数据类型,它会自动推导。添加完之后用dump完成序列化,得到json形式的文本。
#include <iostream>
#include <vector>
#include "json.hpp"
using json_t = nlohmann::json;
int main() {
json_t j; // json对象
// 添加json对象
j["age"] = 21; // "age":23
j["name"] = "diyuyi"; // "name":diyuyi
j["gear"]["suits"] = "2099"; // "gear":{"suits":"2099"}
j["jobs"] = {
"student"}; // "jobs":["student"]
std::vector<int> v = {
1, 2, 3};
j["numbers"] = v; // "numbers":[1, 2, 3]
std::map<std::string, int> m = {
{
"one", 1},{
"two", 2}};
j["map"] = m; // "map":{"one", 1},{"two", 2}
// 序列化得到json文本形式
std::cout << j.dump() << std::endl; // 无缩进
std::cout << j.dump(2) << std::endl; // 缩进两格
}
结果:
{
"age":21,"gear":{
"suits":"2099"},"jobs":["student"],"map":{
"one":1,"two":2},"name":"diyuyi","numbers":[1,2,3]}
{
"age": 21,
"gear": {
"suits": "2099"
},
"jobs": [
"student"
],
"map": {
"one": 1,
"two": 2
},
"name": "diyuyi",
"numbers": [
1,
2,
3
]
}
反序列话功能同样简单,调用静态函数parse即可,直接得到json对象
#include <iostream>
#include <vector>
#include "json.hpp"
using json_t = nlohmann::json;
int main() {
std::string str = R"({"name":"peter","age":23,"married":true})";
json_t j;
try {
j = json_t::parse(str); // 从字符串反序列化
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
assert(j["age"] == 23); // 验证序列化是否正确
}