将Json :: Value转换为std :: string?

BRa*_*t27 31 c++ stdstring jsoncpp

我正在使用JsonCpp来构建一个JSON对象.一旦构建了对象,有没有办法让对象成为一个std::string

Jor*_*yle 36

你可以使用Json :: Writer来做到这一点,因为我假设你想将它保存在某个地方所以你不想要人类可读的输出,你最好的选择是使用Json :: FastWriter然后你可以调用write使用您的Json :: Value(即您的根)的参数的方法,然后只返回std::string如下所示:

Json::FastWriter fastWriter;
std::string output = fastWriter.write(root);
Run Code Online (Sandbox Code Playgroud)

  • 虽然这很好用,但当前版本的JsonCPP表示Json :: FastWriter已被弃用,转而使用Json :: StreamWriterBuilder.但是删除了写入字符串的功能,现在有必要写入std :: stringstream.你能详细说明吗? (5认同)

mar*_*ias 13

Json::Writer不推荐使用,Json::StreamWriterBuilder应该使用,如文档中所述Json::Writer.

Json::writeString 写入字符串流然后返回一个字符串:

Json::Value json = ...;
Json::StreamWriterBuilder builder;
builder["indentation"] = ""; // If you want whitespace-less output
const std::string output = Json::writeString(builder, json);
Run Code Online (Sandbox Code Playgroud)

感谢cdunn2001的回答:如何将JsonCPP值作为字符串?


小智 8

您还可以使用 toStyledString() 方法。

jsonValue.toStyledString();
Run Code Online (Sandbox Code Playgroud)

方法“ toStyledString() ”将任何值转换为格式化字符串。另请参阅链接:toStyledString 的文档