【问题标题】:Parsing a JSON array with an automatically generated mapping throws a NullPointerException使用自动生成的映射解析 JSON 数组会引发 NullPointerException
【发布时间】:2017-01-14 16:16:48
【问题描述】:

如何为 Retrofit 解析以下 JSON 数组?我试过 jsonschema2pojo.org 但我无法生成模型和响应类。它正在给NullPointerException

[
{
"id": "D5mQnyoLClw",
"created_at": "2017-01-14T04:36:41-05:00",
"width": 5760,
"height": 3840,
"color": "#D8DFE3",
"likes": 21,
"liked_by_user": false,
"user": {},
"current_user_collections": [],
"urls": {},
"categories": [],
"links": {}
},
{
"id": "iInYwn194Tk",
"created_at": "2017-01-14T03:53:55-05:00",
"width": 4896,
"height": 2760,
"color": "#FF713E",
"likes": 38,
"liked_by_user": false,
"user": {},
"current_user_collections": [],
"urls": {},
"categories": [],
"links": {}
}]

【问题讨论】:

  • 显示 logcat 输出和导致崩溃的代码。
  • 您的映射代码在哪里?提供迄今为止所做的一切总是好的。

标签: java json gson retrofit


【解决方案1】:

您需要花一些时间阅读Retrofit documentation。有很多例子可以开始。

我建议使用Gson 来处理您的 JSON 对象。

要将所有内容放在一起,您可以查看post

【讨论】:

    【解决方案2】:

    尝试这样做,但我不确定:

    public class Response{
    
    private String id;
    private String created_at;
    private int width;
    private int height;
    private String color;
    private int likes; 
    private boolean linked_by_user;
    
    private user users;
    private List<current_user_collections> list;
    private url urls;
    private List<categories> listcategory;
    private links link;
    
    class user{
    
    }
    
    class current_user_collections{
    
    }
    
    class url{
    
    }
    
    class categories{
    
    }
    
    class links{
    
    }
    
    }
    

    为所有变量创建 getter。

    【讨论】:

    • 但是我只会从中得到一个 json 对象。我可以创建此类但无法创建 json 项数组?
    • 我认为你不能那样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多