C++ POCO - 如何美化JSON?

3

我使用 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"
}

4
你尝试过使用 stringify()indentstep 参数来进行游戏吗? - Dmitry
1
哇!!对不起,我完全忽略了它。您能将答案写在上面,以便我关闭这个问题吗?:) - waas1919
2
我不想在没有自己测试的情况下写出答案,而且今天也没有时间。你可以自行回答。祝你有一个愉快的一天。 - Dmitry
1个回答

9

正如评论中@Dmitry所说,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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接