C++ JSON库json11的使用方法

提纲
1、下载并集成到自己的项目
2、基本用法



1 下载并集成到自己的项目

json11是一个轻量级的C++11库, 提供JSON的序列化和反序列化功能。它的主页是:https://github.com/dropbox/json11。
首先用git clone https://github.com/dropbox/json11.git将json11库下载到本地。

使用时只需要在我们的工程中引入头文件json11.hpp和源文件json11.cpp即可使用。

在自己的项目中只需要include "json11.hpp",就可以在自己的代码中使用json11的库函数了。



2 基本用法

/**
 * 1、将json对象转成json字符串
 */
Json my_json = Json::object {
    { "key1", "value1" },
    { "key2", false },
    { "key3", Json::array { 1, 2, 3 } },
};
std::string json_str = my_json.dump();

/**
 * 2、 将普通对象序列化成json字符串
 *
 */
class Point {
public:
    int x;
    int y;
    Point (int x, int y) : x(x), y(y) {}
    Json to_json() const { return Json::array { x, y }; }
};

std::vector<Point> points = { { 1, 2 }, { 10, 20 }, { 100, 200 } };
std::string points_json = Json(points).dump();

/**
 * 3、将json字符串转成json对象,并取其中的字段,通过这些字段可以进一步构造普通对象
 */
std::string srcJson = "{\"code\":0, \"flag\":true, \"msg\":\"success\"}";

//反序列化为json对象
std::string err;
json11::Json mJson = json11::Json::parse(srcJson, err);

//获取对应字段的值
int code = mJson["code"].int_value();
bool flag = mJson["flag"].bool_value();
std::string msg = mJson["msg"].string_value();

std::cout << "code : " << code << std::endl;
std::cout << "flag : " << flag << std::endl;
std::cout << "msg : " << msg << std::endl;



参考资料
1、https://blog.csdn.net/new9232/article/details/128511137
2、https://github.com/dropbox/json11

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章