如何读取C ++中的JSON内容?

时间:2018-05-24 20:46:31

标签: c++ json c++11 nlohmann-json

我正在尝试读取具有有效JSON内容但不是字符串的文本文件。如果它是一个字符串转储,下面的代码工作正常。例如 - 如果文件内容与此"{ \"happy\": true, \"pi\": 3.141 }"类似,那么它将进行解析而不会出现错误。现在我想找到一种最小化这些转换的方法?如何使用任何标准的lib将JSON内容转换为C ++中的String转储?我现在正在使用nlohmann,但似乎这需要额外的编码。如果我能用简单的代码破解它,请教育我。

我的代码

#include <iostream>
#include <fstream>
#include <streambuf>
#include <nlohmann/json.hpp>

using namespace std;
using json = nlohmann::json;

int main()
{
    std::fstream f_json("C://json.txt");

    json jFile;
    try {
        jFile = json::parse(f_json);
    }
    catch (json::parse_error &e)
    {
        std::cerr << e.what() << std::endl;
    }
    return 0;
}

我们的客户端生成JSON文件,如下所示。

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

2 个答案:

答案 0 :(得分:1)

我的文件位于C:/test.json下,因此它有权打开它。现在我把它放在适当的文件夹中。现在它的工作正常。

答案 1 :(得分:1)

我喜欢使用ThorsSerializer。免责声明是我写的。

#include "ThorSerialize/JsonThor.h"
#include "ThorSerialize/SerUtil.h"
#include <sstream>
#include <iostream>
#include <string>

struct MyObj
{
    bool        happy;
    double      pi;
};
ThorsAnvil_MakeTrait(MyObj, happy, pi);

示例用法:

int main()
{
    using ThorsAnvil::Serialize::jsonImport;
    using ThorsAnvil::Serialize::jsonExport;

    std::stringstream file(R"({ "happy": true, "pi": 3.141 })");

    MyObj   data;
    file >> jsonImport(data);


    std::cout << jsonExport(data) << "\n";
}

输出:

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

对于文件流,它的工作原理相同。但是,您不应转义文件中的"字符。