2016-03-21 63 views
0

我有如下一個JSON: -如何JSON對象轉換成Java jsonReader

{ 
    "products": 
    { 
     "productsApp15": { 
      "code": "productsApp16", 
      "name": "productsApp16", 
      "attribute_set": "Apparel", 
      "product_type": "product", 
      "status": "active" 
      } 
    } 
} 

現在我需要它可以轉換像自動在下面的功能: -

final JsonReader jsonReader = Json.createReader(new StringReader("{\n" + 
       " \"products\":\n" + 
       " {\n" + 
       "  \"productsApp13\": {\n" + 
       "   \"code\": \"productsApp13\",\n" + 
       "   \"name\": \"productsApp13\",\n" + 
       "   \"attribute_set\": \"Apparel\",\n" + 
       "   \"product_type\": \"product\",\n" + 
       "   \"status\": \"active\"\n" + 
       "   }\n" + 
       " }\n" + 
       "}")); 

對於我試圖用/ n連接/連接字符串,但它被佔用爲新行。我知道這是對的,但是有什麼辦法可以自動獲得輸出。

我試過類似下面: -

 String sCurrentLine; 
     StringBuilder sb = new StringBuilder(""); 
     br = new BufferedReader(new FileReader("./src/test/com/testdata/HTTPHelperTest.csv")); 

    while ((sCurrentLine = br.readLine()) != null) { 
     sb.append(sCurrentLine); 
     sb.append("\n"); 
    } 
    br.close(); 
    System.out.println("Value Json"+sb); 

任何解決方案是appreicable。

回答

1

您需要添加一個轉義字符\\n

while ((sCurrentLine = br.readLine()) != null) { 
     sb.append(sCurrentLine); 
     sb.append("\\n"); 
    } 
+0

謝謝..你的答案有給我提供一個部分的律液..投票彌補相同..但它仍然不是像上面做字符串..我也sb.append(「+」); –

+0

那麼,你的第二個代碼示例中存在「+」,因爲已將字符串分隔開以便更好地查看可見性。您可以使用製表符\ t和新行\ n使其看起來像您的問題中的第一個代碼示例。 –