创建自定义GSON反序列化以将JSON响应映射到Android中的对象

时间:2016-04-26 12:37:14

标签: android json gson

我使用GSON库从API映射JSON响应并映射到对象。

这是我的网址链接:

https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty

我的模特课TopStory

public class TopStory implements Comparable<TopStory> {
    int id;
    String title;
    String by;
    int score;
    List<Integer> kids;
    long time;
    String url;



    public TopStory() {
    }

    public TopStory(int id, String title, String by, int score, long time,String url,List kids) {
        this.id = id;
        this.title = title;
        this.by = by;
        this.score = score;
        this.time = time;
        this.url = url;
        this.kids = kids;
    }

并且我创建了一个从JSON响应中创建对象的函数:

public static TopStory fromJson(JSONObject jsonObject) {
        TopStory topStory = new TopStory();
        Gson gson = new Gson();
        topStory = gson.fromJson(jsonObject.toString(),TopStory.class);

我和野外小孩有问题。来自Response,它是JSONARRAY。我们如何反序列化并映射到对象字段List。我如何排除手动反序列化并分配给特定字段?

3 个答案:

答案 0 :(得分:1)

实际上kids不是List,而是Array,所以声明kids就像这样

Integer[] kids;

答案 1 :(得分:0)

您可以使用Retrofit进行api调用,并创建一个可序列化的模型来获取数据。

答案 2 :(得分:0)

尝试使用

Gson gson = new GsonBuilder().create();
TopStory topStory = gson.fromJson(jsonObject.toString(),TopStory.class);

List<Integer> kids; // 更正声明

相关问题