安装JsonCPP
vcpkg install jsoncpp
CMake文件添加
find_package(jsoncpp CONFIG REQUIRED)
target_link_libraries(${PROJECT_NAME} PRIVATE JsonCpp::JsonCpp)
解析Json
#include <iostream>
#include "json/reader.h"
#include "json/value.h"
using namespace std;
int main(int argc, char **argv) {
std::string strJson = R"({"id":4,"name":"Chad","scores":2.99})";
Json::Reader reader;
Json::Value jvRoot;
if (reader.parse(strJson, jvRoot)) {
int nID = jvRoot["id"].asInt();
std::string strName = jvRoot["name"].asString();
double dScores = 0;
if (jvRoot.isMember("scores")) { // 判断是否存在
dScores = jvRoot["scores"].asDouble();
}
cout << nID << ";" << strName << ";" << dScores << endl;
}
return 0;
}
存储Json
#include <iostream>
#include <fstream>
#include "json/writer.h"
#include "json/reader.h"
#include "json/value.h"
using namespace std;
int writeJson() {
Json::Value root;
Json::Value data;
root["code"] = 1001;
root["message"] = "No permission";
if (!data.empty()) { // data可以是m_data成员变量
root["data"] = data;
}
// 保存为字符串
string tmp(root.toStyledString());
cout << tmp << endl;
// 写入文件
std::ofstream ofs("example.json");
Json::StreamWriterBuilder builder;
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
if (writer->write(root, &ofs)) {
cout << "保存成功" << endl;
} else {
cout << "保存失败" << endl;
}
return 0;
}