2017-10-07 63 views
0

我試圖從JSON響應中獲取值。我得到的一切工作,除了從以下字符串中提取一個數組:無法使用GSON將一些JSON解析爲JsonArray

{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"} 

我知道GSON試圖解析它,因爲我得到這個錯誤:

Exception in thread "main" java.lang.IllegalStateException: Not a JSON Array: {"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"} 

我使用下面的代碼試圖解析它:

final JsonElement midElement = obj.get("mid"); 
     final JsonArray midArray = midElement.getAsJsonArray(); 
     for(Object rate : midArray){ 
      final JsonObject rateObj = (JsonObject)rate; 
      final JsonElement openElement = rateObj.get("o"); 
      open = openElement.getAsFloat(); 

      final JsonElement highElement = rateObj.get("h"); 
      high = highElement.getAsFloat(); 

      final JsonElement lowElement = rateObj.get("l"); 
      low = lowElement.getAsFloat(); 

      final JsonElement closeElement = rateObj.get("c"); 
      close = closeElement.getAsFloat(); 
     } 
+0

我想我昨天回答它本身https://stackoverflow.com/questions/46587719/json-object-cannot-be-converted-to-json-array/46587951#46587951 – Optional

+0

Json數組應該括在括號內? {[「o」:「1.18988」,「h」:「1.18993」,「l」:「1.18963」,「c」:「1.18993」]} – kotacc

回答

1

首先它看起來不像一個有效的JSON數組。它應該看起來像這樣

[{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}] 

試試以下代碼以JSON格式解析它。

JSONObject jsonObject = new JSONObject(jsonString); 
    JSONArray jsonArray = jsonObject.getJSONArray("mid"); 
    for (int i = 0; i < jsonArray.length(); i++) {    
     jsonArray.getJSONObject(i).getString("o"); 
    } 

然後將其轉換爲您的首選數據形式。