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

时间:2015-04-17 22:13:27

标签: c++ stdstring jsoncpp

我正在使用JsonCpp来构建JSON对象。构建对象后,有没有办法让对象成为std::string

4 个答案:

答案 0 :(得分:35)

您可以使用Json::Writer来完成此操作,因为我认为您希望将其保存在某个地方以便您不想要人类可读的输出,您最好的选择是使用{{3}然后你可以使用Json::FastWriter的参数(即你的根)调用write方法然后只返回std::string,如下所示:

Json::FastWriter fastWriter;
std::string output = fastWriter.write(root);

答案 1 :(得分:8)

不推荐使用

Json::Writer,而应使用Json::StreamWriterBuilder,如documentation of 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);

感谢cdunn2001的答案:How to get JsonCPP values as strings?

答案 2 :(得分:2)

如果您的Json::value是字符串类型,例如以下json中的“ bar”

{
    "foo": "bar"
}

您可以使用Json::Value.asString来获取bar的值而无需使用额外的引号(如果使用StringWriterBuilder,则会添加引号)。这是一个示例:

Json::Value rootJsonValue;
rootJsonValue["foo"] = "bar";
std::string s = rootJsonValue["foo"].asString();
std::cout << s << std::endl; // bar

答案 3 :(得分:0)

这个小帮手可能会做。

//////////////////////////////////////////////////
// json.asString()
//
std::string JsonAsString(const Json::Value &json)
{
    std::string result;
    Json::StreamWriterBuilder wbuilder;

    wbuilder["indentation"] = "";       // Optional
    result = Json::writeString(wbuilder, json);
    return result;
}