我在這個 json 中有這個配置資料,
{
"difficulty":-1,
"damage":100,
"infinite":true,
"tilewidth":16,
"type":"map",
"version":"1.2.4"
}
我想將這些變數存盤在我的程式中。我不能使用 Map 因為沒有固定型別可供讀取(int、string、bool)...
using JSON = nlohmann::json;
/* struct Configs final {
int difficulty;
int damage;
bool infinite;
int tilewidth;
std::string type;
std::string version;
}; */
int main(void) {
JSON j;
std::ifstream in("./assets/Map.json");
in >> j;
for (auto &el : j.items()) {
std::cout << el.key() << " : " << el.value() << "\n";
}
return 0;
}
有哪些聰明的方法可以做到這一點?
uj5u.com熱心網友回復:
我更喜歡提供一個from_json功能。它可能看起來像這樣:
struct Configs final {
int difficulty;
int damage;
bool infinite;
int tilewidth;
std::string type;
std::string version;
};
void from_json(const json& j, Configs& c) {
j.at("difficulty").get_to(c.difficulty);
j.at("damage").get_to(c.damage);
j.at("infinite").get_to(c.infinite);
j.at("tilewidth").get_to(c.tilewidth);
j.at("type").get_to(c.type);
j.at("version").get_to(c.version);
}
然后,您可以像這樣填充Configs:
in >> j;
auto conf = j.get<Configs>();
uj5u.com熱心網友回復:
您將不得不深入研究 JSON 庫的檔案。弄清楚如何檢查您決議的每個成員的型別。此處的檔案建議from_json為您的類/結構型別創建一個函式。看起來他們提供了一些有用的宏來將 JSON 欄位連接到您的類/結構欄位,例如NLOHMANN_DEFINE_TYPE_NON_INSTRUSIVE
這似乎作業正常
我假設from_json要扔了。確保您處理錯誤。
#include <string>
#include <nlohmann/json.hpp>
using namespace std::string_literals;
static const auto sampleJson = R"(
{
"difficulty":-1,
"damage":100,
"infinite":true,
"tilewidth":16,
"type":"map",
"version":"1.2.4"
}
)"s;
struct Configs final {
int difficulty;
int damage;
bool infinite;
int tilewidth;
std::string type;
std::string version;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Configs, difficulty, damage, infinite, tilewidth, type, version);
using JSON = nlohmann::json;
int main(void)
{
try {
auto j = JSON::parse(sampleJson);
Configs c;
from_json(j, c);
}
catch (...) {
return 1;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412321.html
標籤:
上一篇:如何從NewtonSoft獲取動態物件鍵/值串列反序列化為動態變數
下一篇:Json檔案不可讀?
