首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取Json to object

读取Json to object
EN

Stack Overflow用户
提问于 2020-04-08 04:38:01
回答 1查看 412关注 0票数 0

我当前正在尝试将json文件读取到对象中。我使用的nlohmann-json版本是3.7.3。我遵循了文档中的示例代码,如下所示

代码语言:javascript
复制
// read a JSON file
std::ifstream i("file.json");
json j;
i >> j;

我的实现是有一个简单的函数来返回一个json对象,所以很简单:

代码语言:javascript
复制
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写入文件时,我也遇到了类似的问题

这是我写的一个最小的可重现的例子,它给了我同样的错误;

代码语言:javascript
复制
#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;
}

EN

回答 1

Stack Overflow用户

发布于 2020-04-08 04:39:24

对于nlohmann,我使用这个简单的函数

代码语言:javascript
复制
#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 {};
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61089012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档