提綱
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