Matt W. Matt W. - 6 months ago 37
Java Question

GSON parsing dynamic JSON field

I can't seem to figure this out. I've looked at a couple SO posts (here, and here), and my situation is just a little different.

I'm not sure if I have to register a new TypeToken or what. But my JSON object looks like this:

{
"id": 6,
"error": "0",
"dates": {
34234 : "2011-01-01" // I want to parse the date into a string.
87474 : "2011-08-09" // The first values are all unique.
. //this can be any number of entries.
.
.
74857 : "2011-09-22"
}
}


I've created both of my objects like this:

public class Response {

public Integer id;
public String error;
public DateList dates;
}


Separate file:

public class DateList {

public List<Map<Integer, String>> dateString;
}


I'm not sure how to tweek it to get it right. Documentation doesn't seem to help... And the other examples I've seen are parsing a custom object, not a string type.

Thanks!

Answer

I tried it in this form:

The Json

{
    "id": 6,
    "error": "0",
    "dates": {
        "34234" : "2011-01-01"
        "87474" : "2011-08-09"
        "74857" : "2011-09-22"
    }
}

And the Response.java

public class Response {
    public Integer id;
    public String error;
    public Map<Integer, String> dates;
}

At least that seemed to work out of the box.