2016-06-17 21 views
2

我收到來自PHP服務器的JSON響應。在android中,我需要編寫一個Java模型(POJO)來解析Retrofit(用於http請求的Android庫)中的響應。如何解析在改造中使用Gson Converter的關聯數組?

JSON結構:

{ 
    "calendar": { 
    "2016-06-10": [ 
     { 
     "time": "10h00m", 
     "title": "PROVA P2", 
     "description": "LP/RED/ED.FIS - 80 E 90", 
     "color": "#990000" 
     } 
    ], 
    "2016-06-11": [ 
     { 
     "time": "10h00m", 
     "title": "SIMULADO", 
     "description": "LOREM PSIUM DOLOR LOREM", 
     "color": "#009900" 
     }, 
     { 
     "time": "11h00m", 
     "title": "CONSELHO DE CLASSE", 
     "description": "LOREM PSIUM DOLOR", 
     "color": "#009900" 
     } 
    ] 
    }, 
    "error": false 
} 

JSON是從PHP服務器。 如何使用改造

回答

0

通常情況下,您將創建一個POJO,它代表了您的JSON,但在這種情況下,您需要2016-06-10類和2016-06-11類。

這不是一個解決方案。因此,改變JSON響應作出之日起單獨的值:

{ 
    "calendar": [ 
    { 
     "date": "2016-06-10", 
     "entries": [ 
     { 
      "time": "10h00m", 
      "title": "PROVA P2", 
      "description": "LP/RED/ED.FIS - 80 E 90", 
      "color": "#990000" 
     } 
     ] 
    } 
    ] 
} 

更重要的是,只要一個日期時間值,使其更合適ISO 8601時間戳,而你在它:

{ 
    "calendar": [ 
     { 
     "time": "2016-06-10T08:00:00.000Z", 
     "title": "PROVA P2", 
     "description": "LP/RED/ED.FIS - 80 E 90", 
     "color": "#990000" 
     } 
    ] 
} 

如果你無法控制服務於JSON的服務器,那麼你應該使用Retrofit來獲得一個字符串,並通過gson自己完成Gson轉換。

0

當我不想爲服務器的奇怪響應創建POJO時,我所做的是在java中將其保留爲JSON,並解析字符串以創建JSON對象。 (是的,因爲有時候,我們就無法控制哪些API傢伙編碼...)

由於Cristan說,這將是奇怪的創建2016-06-10類。因此,最好直接將它作爲該特定情況的JSON對象來處理。您可以使用JSON容器訪問任何屬性,並以此方式將其存儲在數據庫中。

你需要什麼,如果你選擇這條道路要做到:

private String sendAlert(String lat, String lon) throws IOException, JSONException { 

    Call<ResponseBody> call = cougarServices.postAlert(lat, lon); 
    ResponseBody response = call.execute().body(); 
    JSONObject json = (response != null ? new JSONObject(response.string()) : null); 
    return handleJsonRequest(json); 

} 
1

要使用動態密鑰解析JSON,你將需要一個MapPOJO類。

以下POJO類添加到您的項目:

  1. CalendarResponse.java

    public class CalendarResponse { 
        @SerializedName("calendar") 
        Map<String, List<Entry>> entries; 
    
        @SerializedName("error") 
        private boolean error; 
    } 
    
  2. Entry.java

    public class Entry { 
        @SerializedName("time") 
        private String time; 
    
        @SerializedName("title") 
        private String title; 
    
        @SerializedName("description") 
        private String description; 
    
        @SerializedName("color") 
        private String color; 
    } 
    
  3. 使用CalendarResponse類的更新接口爲您的端點,見下面的例子

    public interface CalendarService { 
        @GET("<insert your own relative url>") 
        Call<CalendarResponse> listCalendar(); 
    } 
    
  4. 執行呼叫(同步)如下:

    Call<CalendarResponse> call = calendarService.listCalendar(); 
    CalendarResponse result = call.execute().body(); 
    

如果必要,在這裏是解析JSONGSON一個例子:

Gson gson = new GsonBuilder().create(); 
CalendarResponse b = gson.fromJson(json, CalendarResponse.class);