【问题标题】:C++ POCO - How to beautify a JSON?C++ POCO - 如何美化 JSON?
【发布时间】:2018-09-07 08:40:37
【问题描述】:

我使用POCO 库生成一个JSON 文件,如下所示:

void writeToFile()
{
    Poco::JSON::Object::Ptr json = new Poco::JSON::Object;
    json->set("name", "foo");
    json->set("address", "bar");

    std::ostringstream oss;
    Poco::JSON::Stringifier::stringify(json, oss);
    std::ofstream ofs("output.json");
    if (ofs.is_open() == true)
    {
        ofs << oss.str();
        ofs.close();
    }
}

output.json 包含:

{"name":"foo","address":"bar"}

POCO有什么办法可以美化JSON吗?

所以输出会是这样的:

{
    "name" : "foo",
    "address" : "bar"
}

【问题讨论】:

  • 您是否尝试过使用stringify()indentstep 参数?
  • 哇!!对不起,我完全错过了。你能把它写在答案上,这样我就可以结束这个问题了吗?:)
  • 我不想在没有自己测试的情况下写答案,而且我今天没有时间。随意自我回答。祝你有美好的一天。

标签: c++ json poco-libraries


【解决方案1】:

正如@Dmitry 在 cmets 上所说,stringify() 方法上的参数可以:

static void stringify(
    const Dynamic::Var & any,
    std::ostream & out,
    unsigned int indent = 0,
    int step = - 1,
    int options = Poco::JSON_WRAP_STRINGS
);

例子:

Poco::JSON::Stringifier::stringify(json, oss, 4, -1, Poco::JSON_PRESERVE_KEY_ORDER);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 2015-09-24
    • 2021-11-15
    • 2020-04-03
    • 2020-07-13
    相关资源
    最近更新 更多