这是一个初学者的问题, 我如何将以下json字符串数组格式化为std :: string
[
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
}
]
这是json字符串
const std::string json =
"[\n"
" {\n"
" \"x\" : 0,\n"
" \"y\" : 0,\n"
" \"z\" : 0\n"
" },\n"
" {\n"
" \"x\" : 640,\n"
" \"y\" : 0,\n"
" \"z\" : 0\n"
" },\n"
" {\n"
" \"x\" : 640,\n"
" \"y\" : 0,\n"
" \"z\" : 480\n"
" },\n"
" {\n"
" \"x\" : 0,\n"
" \"y\" : 0,\n"
" \"z\" : 480\n"
" }\n"
"]\n";
Json::Value coordinates;
Json::Reader reader;
reader.parse( json, coordinates );
所以我试图解析上面的json数组,得到一个坐标列表,但它无法正确解析。
答案 0 :(得分:4)
您可以使用自C ++ 11以来的原始字符串:
const std::string json = R"(
[
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
}
]
)";
之前,你必须做一些转义为"
- > \"
:
const std::string json =
"[\n"
" {\n"
" \"x\" : 12.1,\n"
" \"y\" : 12.1,\n"
" \"z\" : 12.1\n"
" },\n"
" {\n"
" \"x\" : 12.1,\n"
" \"y\" : 12.1,\n"
" \"z\" : 12.1\n"
" },\n"
" {\n"
" \"x\" : 12.1,\n"
" \"y\" : 12.1,\n"
" \"z\" : 12.1\n"
" },\n"
" {\n"
" \"x\" : 12.1,\n"
" \"y\" : 12.1,\n"
" \"z\" : 12.1\n"
" }\n"
"]\n";