Hackmodford
Hackmodford

Reputation: 3970

How do I handle a Flat JSON Dictionary with Retrofit

My web service returns a json dictionary that represents the id and name of multiple range objects.

{
    "1": "Range 1",
    "2": "Range 2",
    "3": "Range 3"
}

I'm using retrofit with gson and would like the response to be an array of Range objects.

public class Range {
    public Integer persistentId;
    public String name;
}

How do I setup my response class to handle this?

public interface ContentService {
    @GET("/apiv2/release_range_data.json")
    Call<RangeResponse> getRanges();
}

public class RangeResponse {
    public ArrayList<Range> ranges;
}

Do I need a custom deserializer to handle this?

Upvotes: 0

Views: 2073

Answers (1)

Oleg K
Oleg K

Reputation: 5268

how about Map<String, String> and then convert it to a list of Range?

UPD

public class Range {
    public Integer persistentId;
    public String name;
}

public interface ContentService {
    @GET("/apiv2/release_range_data.json")
    Call<RangeResponse> getRanges();
}

public class RangeResponse {
    public Map<String, String> ranges;

    public ArrayList<Range> getRanges() {
        ArrayList<Range> result = new ArrayList<>(ranges.size());
        for(String id : ranges.keySet()) {
            Range range = new Range();
            range.persistentId = Integer.parseInt(id);
            range.name = ranges.get(id);
            result.add(range);
        }
        return result;
    }
}

Upvotes: 3

Related Questions