我当前正在尝试将json文件读取到对象中。我使用的nlohmann-json版本是3.7.3。我遵循了文档中的示例代码,如下所示
// read a JSON file
std::ifstream i("file.json");
json j;
i >> j;我的实现是有一个简单的函数来返回一个json对象,所以很简单:
nlohmann::json UTSF::readJSONFile(std::string filename)
{
std::ifstream i("file.json");
json j;
i >> j;
return j;
}我得到以下错误no operator ">>" matches these operands operand types are: json >> std::ifstream
所以我做了一些调查,在3.7.3版本中不再使用这种方式。我也尝试过使用json.parse,但也不能很好地工作。
对于nlohmann- this版本3.7.3来说,最新的更新方式是什么?在将json写入文件时,我也遇到了类似的问题
这是我写的一个最小的可重现的例子,它给了我同样的错误;
#include <iostream>
#include <nlohmann/json.hpp>
#include <fstream>
using json = nlohmann::json;
nlohmann::json readJSONFile(std::string filename)
{
std::ifstream i(filename);
json j;
i >> j;
return j;
}
int main()
{
nlohmann::json x;
x = readJSONFile("file.json");
std::cout << x.dump(4) << std::endl;
}

发布于 2020-04-08 04:39:24
对于nlohmann,我使用这个简单的函数
#include <nlohmann/json.hpp>
....
nlohmann::json ReadJsonFromFile(std::string file_name) {
try {
return nlohmann::json::parse(std::ifstream{file_name, std::ios::in});
} catch (nlohmann::json::parse_error& e) {
std::cerr << "JSON parse exception : " << e.what() << std::endl;
} catch (std::ifstream::failure& e) {
std::cerr << "Stream exception : " << e.what() << std::endl;
} catch (std::exception& e) {
std::cerr << "Exception : " << e.what() << std::endl;
} catch (...) {
std::cerr << "Unk error" << std::endl;
}
return {};
}https://stackoverflow.com/questions/61089012
复制相似问题