欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

c++讀json 的方法

劉柏宏2年前11瀏覽0評論

C++ 中讀取 JSON 格式的數據,一般需要使用第三方庫進行解析,常用的庫有jsoncpp、rapidjson、nlohmann/json 等。

1. jsoncpp

#include <json/json.h>
int main()
{
std::string json_str = "{ \"name\": \"John\", \"age\": 30 }";
Json::CharReaderBuilder builder;
Json::CharReader *reader = builder.newCharReader();
Json::Value root;
JSONCPP_STRING errs;
bool ok = reader->parse(json_str.c_str(), json_str.c_str() + json_str.length(), &root, &errs);
if (ok) {
std::string name = root["name"].asString();
int age = root["age"].asInt();
std::cout << "name: " << name << ", age: " << age << std::endl;
}
delete reader;
return 0;
}

2. rapidjson

#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
int main()
{
const char* json_str = "{ \"name\": \"John\", \"age\": 30 }";
rapidjson::Document d;
d.Parse(json_str);
if (d.IsObject()) {
std::string name = d["name"].GetString();
int age = d["age"].GetInt();
std::cout << "name: " << name << ", age: " << age << std::endl;
}
return 0;
}

3. nlohmann/json

#include "nlohmann/json.hpp"
using json = nlohmann::json;
int main()
{
std::string json_str = "{ \"name\": \"John\", \"age\": 30 }";
json j = json::parse(json_str);
if (j.is_object()) {
std::string name = j["name"];
int age = j["age"];
std::cout << "name: " << name << ", age: " << age << std::endl;
}
return 0;
}