2017-10-10 149 views
-5

我有以下的JSONObject如何從JSONObject的元素獲取並寫入到文件

   {"elements": [ 
       { 
       "name": "StartLabelFormat", 
       "value": "^XA" 
       }, 
       { 
       "name": "shipperAddressLine1", 
       "value": "Street1", 
       "format": {"Text": { 
        "orientation": "N", 
        "height": "28", 
        "width": 20, 
        "fontname": 0, 
        "y": 373, 
        "x": 20 
       }} 
       }, 
       { 
       "name": "EndLabelFormat", 
       "value": "^XZ" 
       } 
      ]} 

現在我想從這個對象獲取元素,並將其寫入文件。 例如,對於該塊

{ 
       "name": "shipperAddressLine1", 
       "value": "Street1", 
       "format": {"Text": { 
        "orientation": "N", 
        "height": "28", 
        "width": 21, 
        "fontname": 0, 
        "y": 373, 
        "x": 20 
       }} 
       }, 

我想在文件作爲 ^ FT 20,373^A0N,28個,21^FDStreet1^FS來寫。

請幫我做到這一點。

+0

這不是一個編碼服務。自己做一些工作。 – Sedrick

+0

你能檢查我的答案嗎? – KeLiuyue

回答

0

如何做到這一點?

  • 如果你在你的代碼滿足{},您可以使用JSONObject解析它。

  • 如果您在代碼中遇到[],則可以使用JSONArray來解析它。

  • 如果您在代碼中遇到[],則可以使用for loop來獲取其中的值。您的代碼中應該使用try catch

在您的代碼中試試這個。

try { 
     JSONObject jsonObject = new JSONObject(response); 
     JSONArray elements = jsonObject.getJSONArray("elements"); 
     for (int i = 0; i < elements.length(); i++) { 
      JSONObject jsonObject1 = elements.getJSONObject(i); 
      String name = jsonObject1.optString("name"); 
      String value = jsonObject1.optString("value"); 
      JSONObject format = jsonObject1.optJSONObject("format"); 
      JSONObject Text = format.optJSONObject("Text"); 
      String orientation = Text.optString("orientation"); 
      String height = Text.optString("height"); 
      String width = Text.optString("width"); 
     } 
} catch (JSONException e) { 
     e.printStackTrace(); 
} 

注意

  • 而且在代碼中使用optStringoptJSONObject。如果formatnull,它不會返回錯誤。

  • 而且你可以判斷JSONArraylength不是0而不是null在代碼中。

+0

感謝您的幫助@KeLiuyue,我可以獲取數據,但我應該如何將它寫入文件。JSONArray中可能包含更多格式或maynot。基本上我有寫從這個的JSONObject一個文件,如 '^'XA' ^ LH16,12'' ^ LL1212' '^ FT 20,313^A0N,28個,20^FD Street1^FS' '^FT 20,343^A0N,28,20^FD US^FS' '^ XZ – neo

-1

從JsonArray

得到這個元素
JsonObject yourElement = yourJsonArray.get(index); 

簡單地說,你可以使用GSON庫解析JSON對象。

public class Staff { 

private String name; 
private String value; 

//... 

,並使用GSON

String jsonInString = " { 
      "name": "shipperAddressLine1", 
      "value": "Street1" 
      }"; 
Staff staff = gson.fromJson(yourElement.toString() , Staff.class); 

之後,你可以通過使用人員類中自定義toString()方法在文件中寫道。 P.S.將JsonObject轉換爲String也可以使用toString()方法。