2013-01-16 338 views
1

我有以下JSON響應。GSON拋出「期望的BEGIN_OBJECT但是BEGIN_ARRAY」?

{"message":"[{\"first_name\":\"Sushant\",\"last_name\":\"Bhatnagar\",\"receiver_id\":\"19\",\"docket_number\":\"Test12\",\"status\":\"open\"}]","code":200,"format":"json"} 

,我必須創建兩個類,如下解析它: -

 public class JsonResponse implements Serializable { 

public String code; 
public String format; 
public List<Message> message; 

}

公共類信息實現Serializable {

public String first_name; 
public String last_name; 
public String receiver_id; 
public String docket_number; 
public String status; 

}

使用G用於解析json的SOAP,獲取以上錯誤。代碼解析JSON是: -

  public static JsonResponse readDockets(String mobileNumber) { 
    JsonResponse res = new JsonResponse(); 
    HttpClient client = new DefaultHttpClient(); 
    String service = "http://api.pod.iamwhiney.com:8994/api.php?path=/deliveryRecord/refresh/"+"9968395206"; 
    HttpGet httpGet = new HttpGet(service); 
    try { 
     HttpResponse response = client.execute(httpGet); 
     StatusLine statusLine = response.getStatusLine(); 
     int statusCode = statusLine.getStatusCode(); 
     if (statusCode == 200) {    

      HttpEntity getResponseEntity = response.getEntity(); 
      InputStream httpResponseStream = getResponseEntity.getContent(); 
      Reader inputStreamReader = new InputStreamReader(httpResponseStream);    
      Gson gson = new Gson(); 
      res = gson.fromJson(inputStreamReader, JsonResponse.class); 

     } else { 

     } 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return res; 
} 

回答

0

JSon字符串應該是這種格式:

{ 
    sections: 
     [ 
      { 
      "SectionId": 1, 
      "SectionName": "Android" 
      } 
     ] 
} 
0

我不知道爲什麼你使用GSON,由於Android有它自己建立JSON解析器。至於你得到的錯誤......這是因爲你解析的JSON是JSONArray,而不是JSONObject。我不太知道什麼@Yaqub在看,但你的JSON響應應該如下:

{"message":  
    {"first_name":"Sushant", 
    "last_name":"Bhatnagar"..... 
    "status":"open" 
    },"code":"200","format":"json"} 

也就是說,沒有周圍的內容[],因爲這告訴JSON解析器,這是一個JSON只有1個索引的數組,而您顯然需要單個JSON對象。上面的JSONString將允許你解析它,你可以從'message'標籤中獲得一個JSONObject。

注意:我已經刪除了轉義,因爲我想通過解析器運行我的編輯,但是您可以輕鬆地將它們添加回來,並且它仍然可以工作。

注意:在"code":200在原始JSON必須"code":"200"否則你會得到另一個錯誤有

相關問題