Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...