将 json::value 转换为 std::string
Converting a Json::Value to std::string?
我正在使用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::StreamWriter
或Json::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;
}
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL