将 json::value 转换为 std::string

Converting a Json::Value to std::string?

本文关键字:std string value json 转换      更新时间:2023-10-16

我正在使用JsonCpp来构建一个JSON对象。构建对象后,有没有办法将对象作为std::string获取?

您可以使用

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

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

Json::Writer已被弃用。请改用Json::StreamWriterJson::StreamWriterBuilder

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的答案:如何获取JsonCPP值作为字符串?

你也可以使用 to StyledString() 方法。

jsonValue.toStyledString();

方法"toStyledString()"将任何值转换为格式化字符串。另请参阅链接:doc for toStyledString

如果你的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

在我的上下文中,我在json值对象的末尾使用了一个简单的.asString()。正如@Searene所说,如果您想之后处理它,它

摆脱了您不需要的额外报价。
Json::Value credentials;
Json::Reader reader;
// Catch the error if wanted for the reader if wanted. 
reader.parse(request.body(), credentials);
std::string usager, password;
usager = credentials["usager"].asString();
password = credentials["password"].asString();

如果值是 int 而不是字符串,.asInt() 也可以很好地工作。

这个小帮手可能会。

//////////////////////////////////////////////////
// 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;
}