5

我是 java/Android 的初学者,我尝试用 Gson 解析 JSON。

我在文件部分遇到了一些困难。从我读过的内容来看,我应该使用 MapHash,但我不确定如何在这段代码中使用它

这是我的主要课程

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

进行解析的类

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结构

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

谢谢你的帮助

这是我尝试解析的 JSon 结构的编辑文件 http://jsontest.web44.net/noauth.json

4

1 回答 1

5

在您的File班级中,您有 2 个属性:ValueXURLX. 但是在您的 JSON 中,您有 2 个字段NameA并且NameB...

JSON 响应中的名称和您的类必须匹配,否则您将无法获得任何值...

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...

于 2013-05-25T23:11:48.617 回答