这是一个初学者问题,我将如何将以下 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
}
]
Run Code Online (Sandbox Code Playgroud)
这是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 );
Run Code Online (Sandbox Code Playgroud)
所以我试图解析上面的json数组,以获取坐标列表,但无法正确解析。
从 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
}
]
)";
Run Code Online (Sandbox Code Playgroud)
之前,你必须做一些转义"-> \":
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";
Run Code Online (Sandbox Code Playgroud)