2016-06-17 22 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);