【问题标题】:C++: Reading a json object from file with nlohmann jsonC++:使用 nlohmann json 从文件中读取 json 对象
【发布时间】:2016-02-11 05:28:03
【问题描述】:

我正在使用 nlohmann 的 json 库来处理 c++ 中的 json 对象。最终,我想从文件中读取一个 json 对象,例如像这样的一个简单对象。

{
"happy": true,
"pi": 3.141
}

我不太确定如何处理这个问题。在https://github.com/nlohmann,提供了几种从字符串文字反序列化的方法,但是将其扩展为读取文件似乎并不简单。有任何人对此有经验吗?

【问题讨论】:

    标签: c++ json file nlohmann-json


    【解决方案1】:

    2017-07-03 更新 JSON for Modern C++ version 3

    3.0 版 起,json::json(std::ifstream&) 已被弃用。应该改用json::parse()

    std::ifstream ifs("test.json");
    json jf = json::parse(ifs);
    
    std::string str(R"({"json": "beta"})");
    json js = json::parse(str);
    

    有关如何使用 nlohmann 的 json 库的更多基本信息,请参阅nlohmann FAQ


    现代 C++ 版本 2 的 JSON 更新

    2.0 版 开始,json::operator>>() id deprecated。应该改用json::json()

    std::ifstream ifs("{\"json\": true}");
    json j(ifs);
    

    现代 C++ 版本 1 的 JSON 的原始答案

    使用json::operator>>(std::istream&):

    json j;
    std::stringstream ifs("{\"json\": true}");
    ifs >> j;
    

    【讨论】:

    • 您好,对于 2.0.0 版本,我添加了一个构造函数来直接处理输入流,因此您可以编写 json j(ifs);。有关详细信息,请参阅nlohmann.github.io/json/…
    【解决方案2】:

    构造函数json j(ifs) 已弃用,将在版本 3.0.0 中删除。从 2.0.3 版开始,你应该写:

    std::ifstream ifs("test.json");
    json j = json::parse(ifs);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多