github文件:https://github.com/nlohmann/json#read-json-from-a-file
只需在需要使用的文件中#include“json.hpp”
C++含义
.hpp
,其实质就是将. cpp
的实现代码混入. h
头文件当中,定义与实现都包含在同一文件,则该类的调用者只需要include该hpp
文件即可,无需再
将cpp
加入到project中进行编译。
给出相应的json文件
//example.json
{"pi": 3.141,"happy": true,"name": "Niels","nothing": null,"answer": {"everything": 42},"list": [1,0,2],"object": {"currency": "USD","value": 42.99},"add": 10
}
#include
#include
#includeusing json = nlohmann::ordered_json;//这边为按照json文件的实际内容顺序读取
using namespace std;
void main()
{//读取方式1std::ifstream f("example.json");json data = json::parse(f);//读取方式2std::ifstream i("example.json");json j;i >> j;//构造方式1json j;j["pi"] = 3.141;j["happy"] = true;j["name"] = "Niels";j["nothing"] = nullptr;j["answer"]["everything"] = 42;j["list"] = { 1, 0, 2 };j["object"] = { {"currency", "USD"}, {"value", 42.99} };//构造方式2int num = 42;json j2 = {{"pi", 3.141},{"happy", true},{"name", "Niels"},{"nothing", nullptr},{"answer", {{"everything", num}}},{"list", {1, 0, 2}},{"object", {{"currency", "USD"},{"value", 42.99}}}};j2["add"] = 10;//输出std::ofstream o("pretty.json");o << std::setw(4) << j2 << std::endl;
}
定义结构体
struct Player{string name;int credits;int ranking;
};
void to_json(nlohmann::json& j, const Player& p)
{j = json{ {"name", p.name}, {"credits", p.credits}, {"ranking", p.ranking} };
}
void from_json(const nlohmann::json& j, Player& p)
{j.at("name").get_to(p.name);j.at("credits").get_to(p.credits);j.at("ranking").get_to(p.ranking);
}
通过在字符串尾部追加 _json
来将 string
类型的字面值进行转化:
// create object from string literal
json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;// or even nicer with a raw string literal
auto j2 = R"({"happy": true,"pi": 3.141}
)"_json;如果不添加`_json`, 传递的string类型的数值不会被转化为。当然,也可以直接显式的进行
```c++
// parse explicitly
auto j3 = json::parse(R"({"happy": true, "pi": 3.141})");
将json
格式的对象转化为string
类型的字符串:
// explicit conversion to string
std::string s = j.dump(); // {"happy":true,"pi":3.141}// serialization with pretty printing
// pass in the amount of spaces to indent
std::cout << j.dump(4) << std::endl;
// {
// "happy": true,
// "pi": 3.141
// }
上一篇:图书管理系(附源码PPT)