简体   繁体   中英

Parsing json data with retrofit android

i'm trying to parse json to created class but i receive null at field of this class.

json looks like this:

{"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" }
    ]
}

Here is method of retrofit:

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;
    }

Class Ping:

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

//getters, setters
}

I receive object of class WorkingMonth but field workingDays is null. Help would be much appreciated. Thanks!

UPDATE

I have found solution. I had to write my custom map deserializer

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);
    }
}

and then

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM