Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson with dynamic name (Android)

I'm a beginner in java/Android and I try to parse JSON with Gson.

I'm having some difficulty with the files part. From what I've read I should use MapHash but I'm not sure how to use it in this code

Here my Main class

InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
SearchResponse response = gson.fromJson(reader, SearchResponse.class);

The class that do the parsing

public class SearchResponse {

    public List<Podcast> podcasts; 

    class Podcast {

        @SerializedName("files")
        private List<File> files;

        @SerializedName("format")
        private String format;

        @SerializedName("title")
        private String title;

    class File {
        private String ValueX;
        private String URLX;
        }
    }
}

json structure

{
"podcasts": [
    {
    "files": [
        {"NameA": "ValueA"},
        {"NameB": "ValueB"},
        {"...": "..."}
    ],
    "format": "STRING",
    "title": "STRING"
    }
    ]
}

Thanks for your help

here's an edited file of the structure of the JSon I try to parse http://jsontest.web44.net/noauth.json

like image 752
Keven Avatar asked May 25 '13 21:05

Keven


1 Answers

In your File class you have 2 attributes: ValueX and URLX. But in your JSON you have 2 fields NameA and NameB...

Names in JSON response and your class must match, otherwise you won't get any value...

Apart from that, your class structure looks good, and your code for deseralizing looks good as well... I don't think you need any HashMap...


EDIT: Taking into account your comment, you could use a HashMap. You could change your Podcast class using:

@SerializedName("files")
private List<Map<String,String>> files;

And you should get it parsed correctly.

You have to use a List because you have a JSON array (surrounded by [ ]), and then you can use the Map to allow different field names.

Note that you have to delete your File class...

like image 156
MikO Avatar answered Sep 28 '22 10:09

MikO