2017-02-18 112 views
0

我想解析json創建類,但我收到這個類的字段爲null。解析json數據與改造android

JSON看起來是這樣的:

{"13": [ 
    { "id": 3654, "dateIn": "2017-02-13 13:13:13", "dateOut": "2017-02-13 15:13:13" }, 
    { "id": 3656, "dateIn": "2017-02-13 17:13:13", "dateOut": "2017-02-13 17:13:13" }, 
    { "id": 3655, "dateIn": "2017-02-13 16:13:13", "dateOut": "2017-02-13 17:13:13" } 
    ], 
"14": [ 
    { "id": 3654, "dateIn": "2017-02-13 13:13:13", "dateOut": "2017-02-13 15:13:13" }, 
    { "id": 3656, "dateIn": "2017-02-13 17:13:13", "dateOut": "2017-02-13 17:13:13" }, 
    { "id": 3655, "dateIn": "2017-02-13 16:13:13", "dateOut": "2017-02-13 17:13:13" } 
    ] 
} 

這裏是改造的方法:

Call<WorkingMonth> callPings = HelperClass.getService().getPing(month, year); 
callPings.enqueue(new Callback<WorkingMonth>() { 
    @Override 
    public void onResponse(Call<WorkingMonth> call, Response<WorkingMonth> response) { 
     if (response.isSuccessful()) { 
      WorkingMonth wm = response.body(); 
      wm.getWorkingDays(); 
     } else { 

      Log.i(TAG, "error in downloading"); 
     }  
    } 

    @Override 
    public void onFailure(Call<WorkingMonth> call, Throwable t) { 

     Log.i(TAG, t.toString()); 
    } 
}); 

類WorkingMonth:

public class WorkingMonth{ 

    private Map<String,List<Ping>> workingDays; 

    public Map<String,List<Ping>> getWorkingDays() { 
     return workingDays; 
    } 

    public void setWorkingDays(Map<String,List<Ping>> workingDays) { 
     this.workingDays = workingDays; 
    } 

類平:

public class Ping { 
private Long id; 
private String dateIn; 
private String dateOut; 

//getters, setters 
} 

我收到類WorkingMonth的對象,但字段workingDays爲null。 幫助將不勝感激。謝謝!

UPDATE

我已經找到了解決方案。我不得不寫我的自定義地圖解串器

private class HolderDeserializer implements JsonDeserializer<WorkingMonth> { 

    @Override 
    public WorkingMonth deserialize(JsonElement json, Type type, JsonDeserializationContext context) 
      throws JsonParseException { 

     Type mapType = new TypeToken<Map<String, List<Ping>>>() {}.getType(); 
     Map<String, List<Ping>> data = context.deserialize(json, mapType); 

     return new WorkingMonth(data); 
    } 
} 

然後

HolderDeserializer holderDeserializer = new HolderDeserializer(); 
GsonBuilder gsonBuilder = new GsonBuilder(); 
gsonBuilder.registerTypeAdapter(WorkingMonth.class, holderDeserializer); 
Gson gson = gsonBuilder.create(); 

Type responseType = new TypeToken<WorkingMonth>() {}.getType(); 
WorkingMonth response = gson.fromJson(json, responseType); 
+0

您使用的是什麼轉換器?默認情況下,內置的轉換器都不將鍵和值映射到HashMap。 – akash93

+0

Btw @Blackbelt'@ Expose'是沒有意義的,除非你明確地設置'GsonBuilder.excludeFieldsWithoutExposeAnnotation()' – akash93

+0

@ akash93我使用的是gson。我已經找到解決方案。我不得不寫我自己的地圖解串器。問題用解決方案更新。謝謝 – mesomagik

回答