2017-08-30 29 views
0

這是一個初學者的問題, 我怎麼會格式字符串以下JSON數組的std :: string格式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

的Json * *是一個字符串。這不是代碼。 '「[{」x:12.1},{「x」:12.1「}]」'是一個Json字符串。你什麼意思?您是否試圖創建一個 –

+0

我的問題如何將json寫入std :: string – andre

+0

就像任何其他字符串一樣。 Json是一個字符串,其內容具有特定的格式。而已。 –

回答

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"; 
+0

在他必須逃脫'\ n'之前。爲完整性:http://en.cppreference.com/w/cpp/language/string_literal請參閱:前綴(可選)R「分隔符(raw_characters)分隔符」\t(6)\t(自C++ 11)'。 –

+0

謝謝你的作品! – andre

+0

您可以在沒有Raw的情況下編寫它,只是爲了獲得完整答案 – andre

相關問題