这里使用的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;
j["age"] = 21;
j["name"] = "diyuyi";
j["gear"]["suits"] = "2099";
j["jobs"] = {"student"};
std::vector<int> v = {1, 2, 3};
j["numbers"] = v;
std::map<std::string, int> m = {{"one", 1},{"two", 2}};
j["map"] = m;
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);
}
|