在C++中使用JSON,首先需要导入JSON库。
这里我们使用的是nlohmann/json库,这个库只需要引用其提供的json.hpp
文件即可使用,没有任何依赖,也不需要复杂的构建过程。
下载
点击此处可以下载 JSON for Modern C++ version 3.11.3
需要其他版本可以查看Github仓库
的release
。
将其放置在编译可寻地址(最简单的是放在源文件的目录下)。
别名
#include "json.hpp"
// 使用json作为nlohmann::json的别名
using json = nlohmann::json;
序列化
string serialization() {
// 声明一个nlohmann::json对象。
json js;
// 添加三个项
js["id"] = 1;
js["name"] = "CodeSingerAlex";
js["password"] = "password";
// 将nlohmann::json对象转换为JSON格式的字符串。
string request = js.dump();
cout << request << endl;
return request;
}
反序列化
void deserialization(string &request) {
json js = json::parse(request);
std::cout << js["id"] << std::endl;
std::cout << js["name"] << std::endl;
std::cout << js["password"] << std::endl;
}
完整代码
#include "json.hpp"
#include <iostream>
#include <string>
using namespace std;
using json = nlohmann::json;
string serialization() {
// 声明一个nlohmann::json对象。
json js;
// 添加三个项
js["id"] = 1;
js["name"] = "CodeSingerAlex";
js["password"] = "password";
// 将nlohmann::json对象转换为JSON格式的字符串。
string request = js.dump();
cout << request << endl;
return request;
}
void deserialization(string &request) {
// 将request解析为nlohmann::json对象。
json js = json::parse(request);
// 输出对应键的值
std::cout << js["id"] << std::endl;
std::cout << js["name"] << std::endl;
std::cout << js["password"] << std::endl;
}
int main() {
string request = serialization();
deserialization(request);
}
注意编译是需要加-std=c++11
选项,因为nlohmann/json
库是用C++11
编写的,编译命令类似:
g++ -std=c++11 jsontest.cpp -o jsontest
输出
{"id":1,"name":"CodeSingerAlex","password":"password"}
1
"CodeSingerAlex"
"password"