赞
踩
最好用的c++ json库是 nlohmann
github 地址:https://github.com/nlohmann/json.git
把变量写成json容易,可是把json变成变量就要复杂一点,不过对于nlohmann一点都不复杂
不多说了
编译安装
mkdir build
cd build
cmake ..
make
sudo make install
#include "nlohmann/json.hpp" //实际位置在 /usr/include中,so和a文件也在默认的地方
#include "nlohmann/json.hpp" #include <iostream> #include <fstream> #include <eigen3/Eigen/Eigen> using json = nlohmann::json; using namespace std; using namespace Eigen; int main() { nlohmann::json json; Eigen::Vector3d o(3,4,5); Eigen::Quaterniond origin_(2, 0, 1, -3); json["id"] = id; json["map_type"] = type_; nlohmann::json json_origin_position; json_origin_position["x"] = o.x(); json_origin_position["y"] = o.y(); json_origin_position["z"] = o.z(); nlohmann::json json_origin_rotation; json_origin_rotation["w"] = origin_.w(); json_origin_rotation["x"] = origin_.x(); json_origin_rotation["y"] = origin_.y(); json_origin_rotation["z"] = origin_.z(); nlohmann::json json_origin; json_origin["position"] = json_origin_position; json_origin["rotation"] = json_origin_rotation; json["origin"] = json_origin; cout << json.dump(2) << std::endl; std::ofstream os("test.json"); os << json.dump(4) << endl; return 0; }
json["somename"].get<T>()
,如 basictype x = json["somename"].get<basictype>();
json.at("somename").get_to(variable)
from_json(const json& json, T& var)
struct hl{
int id;
};
}
hl m = json["name"].get<hl>(); //错误
需要为struct hl
加上序列化方法from_json(const json& json, hl* var)
修改上面的struct hl
为
struct hl{
int id;
};
void from_json(const json& j, hl& h){
j.at("id").get_to(h.id);
}
hl m = json["name"].get<hl>(); //正确
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。