我正在尝试解析json到创建的类,但我在这个类的字段中收到null。
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());
}
});
Class 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;
}
班级Ping:
public class Ping {
private Long id;
private String dateIn;
private String dateOut;
//getters, setters
}
我收到WorkMonth类的对象但是field workingDays是null。 非常感谢帮助。谢谢!
更新
我找到了解决方案。我不得不写自定义地图反序列化器
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);