将 json 代码格式化为 std::string

and*_*dre 1 c++ json

这是一个初学者问题,我将如何将以下 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数组,以获取坐标列表,但无法正确解析。

Jar*_*d42 5

从 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)

  • @andre 发布重现您的问题并包含完整错误消息的 *实际* 代码。可能是您使用了无效标签,或者缺少必需的标签。或者它可能是解析器库的一个怪癖。什么是`Json::Reader`? (3认同)