【问题标题】:Volley parsing Json response is null AndroidVolley解析Json响应为空Android
【发布时间】:2016-06-14 14:05:50
【问题描述】:

我正在尝试使用 volley 解析 JSON 对象,但它会将所有值都设为 null

我正在使用 GsonRequest 自定义类来使用 GSON 库进行解析

public class GsonRequest < T > extends JsonRequest < T > {

    /** Charset for request. */
    private static final String PROTOCOL_CHARSET = "utf-8";

    /** Content type for request. */
    private static final String PROTOCOL_CONTENT_TYPE = String.format("application/json; charset=%s", PROTOCOL_CHARSET);

    private final Gson mGson;
    //private final String mBody;
    private final Class < T > clazz;
    private final Listener < T > listener;
    private final Map < String,
    String > headers;
    private final String mBody;

    public GsonRequest(int method, String url, String body, Class < T > clazz, Map < String, String > headers, Response.Listener < T > listener, Response.ErrorListener errorListener) {
        super(method, url, (body == null) ? null: body, listener, errorListener);
        this.clazz = clazz;
        this.mBody = body;
        this.headers = headers;
        this.listener = listener;
        mGson = new Gson();
    }@Override
    public Map < String,
    String > getHeaders() throws AuthFailureError {
        return headers != null ? headers: super.getHeaders();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response < T > parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(mGson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
        } catch(UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch(JsonSyntaxException e) {
            Log.e("JsonSyntaxException", " " + e);
            return Response.error(new ParseError(e));
        }
    }
}

我使用http://www.jsonschema2pojo.org/ 创建了模型类,下面是我的模型类

public class ModelConnection {

    private List < Datum > data = new ArrayList < Datum > ();
    private Integer code;
    private Object message;
    private Map < String,
    Object > additionalProperties = new HashMap < String,
    Object > ();

    /**
     * 
     *  @return
     *  The data
     */
    public List < Datum > getData() {
        return data;
    }

    /**
     * 
     * @param data
     *     The Data
     */
    public void setData(List < Datum > data) {
        this.data = data;
    }

    /**
     * 
     * @return
     *     The code
     */
    public Integer getCode() {
        return code;
    }

    /**
     * 
     * @param code
     *     The Code
     */
    public void setCode(Integer code) {
        this.code = code;
    }

    /**
     * 
     * @return
     *     The message
     */
    public Object getMessage() {
        return message;
    }

    /**
     * 
     * @param message
     *     The Message
     */
    public void setMessage(Object message) {
        this.message = message;
    }

    public Map < String,
    Object > getAdditionalProperties() {
        return this.additionalProperties;
    }

    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    public class Datum {

        private Integer userID;
        private String firstName;
        private String lastName;
        private String title;
        private String organization;
        private String industry;
        private String location;
        private String profileSummary;
        private String imagePath;
        private List < Object > interests = new ArrayList < Object > ();
        private Map < String,
        Object > additionalProperties = new HashMap < String,
        Object > ();

        /**
         *
         * @return
         *     The userID
         */
        public Integer getUserID() {
            return userID;
        }

        /**
         *
         * @param userID
         *     The UserID
         */
        public void setUserID(Integer userID) {
            this.userID = userID;
        }

        /**
         *
         * @return
         *     The firstName
         */
        public String getFirstName() {
            return firstName;
        }

        /**
         *
         * @param firstName
         *     The FirstName
         */
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        /**
         *
         * @return
         *     The lastName
         */
        public String getLastName() {
            return lastName;
        }

        /**
         *
         * @param lastName
         *     The LastName
         */
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        /**
         *
         * @return
         *     The title
         */
        public String getTitle() {
            return title;
        }

        /**
         *
         * @param title
         *     The Title
         */
        public void setTitle(String title) {
            this.title = title;
        }

        /**
         *
         * @return
         *     The organization
         */
        public String getOrganization() {
            return organization;
        }

        /**
         *
         * @param organization
         *     The Organization
         */
        public void setOrganization(String organization) {
            this.organization = organization;
        }

        /**
         *
         * @return
         *     The industry
         */
        public String getIndustry() {
            return industry;
        }

        /**
         *
         * @param industry
         *     The Industry
         */
        public void setIndustry(String industry) {
            this.industry = industry;
        }

        /**
         *
         * @return
         *     The location
         */
        public String getLocation() {
            return location;
        }

        /**
         *
         * @param location
         *     The Location
         */
        public void setLocation(String location) {
            this.location = location;
        }

        /**
         *
         * @return
         *     The profileSummary
         */
        public String getProfileSummary() {
            return profileSummary;
        }

        /**
         *
         * @param profileSummary
         *     The ProfileSummary
         */
        public void setProfileSummary(String profileSummary) {
            this.profileSummary = profileSummary;
        }

        /**
         *
         * @return
         *     The imagePath
         */
        public String getImagePath() {
            return imagePath;
        }

        /**
         *
         * @param imagePath
         *     The ImagePath
         */
        public void setImagePath(String imagePath) {
            this.imagePath = imagePath;
        }

        /**
         *
         * @return
         *     The interests
         */
        public List < Object > getInterests() {
            return interests;
        }

        /**
         *
         * @param interests
         *     The Interests
         */
        public void setInterests(List < Object > interests) {
            this.interests = interests;
        }

        public Map < String,
        Object > getAdditionalProperties() {
            return this.additionalProperties;
        }

        public void setAdditionalProperty(String name, Object value) {
            this.additionalProperties.put(name, value);
        }

    }

}

这是来自其他客户端的响应

{
  -"Data": [2]
  -0:  {
        "UserID": 124
        "FirstName": "Mixer"
        "LastName": "Development"
        "Title": "Flipdex Architect "
        "Organization": "CoStrategix"
        "Industry": "Software "
        "Location": "Bengaluru Area, India"
        "ProfileSummary": "Mixer#^*+~|Software engineer?????????? 123456789"@&$)(;:/-.,?!ASDFZgZhXjZkZlZXCVZbNZmQWERTYUIOZp[]{}#%^*+¥£€><~|\_.,?! "
        "ImagePath": "https://media.licdn.com/mpr/mprx/0_tiUBxkxpFtDhAIKrczfJBnzj6FMhlWiAOiiJJAUpF8YTlJayP3DBA3Mp5NrycIrrczfJ48nymk-3-DwljKYwBKBKIk-8-DErYKYNylCgh5F24Rlu-3HVpLuuwAHKUDj3c1VURiTsxsU"
        "Interests": [0]
      }

  -1: {
        "UserID": 153
        "FirstName": "Mixer"
        "LastName": "Android"
        "Title": "Assistant Manager at CoStrategix"
        "Organization": "CoStrategix"
        "Industry": "Software"
        "Location": "Bengaluru Area, India"
        "ProfileSummary": "We have worked with over 35+ product companies and bring the critical thinking and technology expertise to launching your product. We have l"
        "ImagePath": "https://media.licdn.com/mpr/mprx/0_0EwKKqh9nkV0X1t3pmPYj6B9ncH0T_TTJy0K9h29KnTYT1u8zElOR_C9q3zGb1gDJyjY4_SnOQUOGFf8zJmuZhhsUQUxGFHTzJmPP3zBKbm1HA1jMe4j1vRQR1T7wFxKysoyq1W3CaQ"
        "Interests": [0]
      }

   "Code": 1
   "Message": null
}

这就是我调用 api 的方式

GsonRequest request = new GsonRequest(Request.Method.GET, newConnectionAPI,null, ModelConnection.class, getHeaders(),
            new Response.Listener<ModelConnection>() {
                @Override
                public void onResponse(ModelConnection response) {
                    if (listener != null) {
                        listener.networkResponseSuccessful(response);
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("volley error", "" + error);
        }
    });
    request.setTag(tag);
    request.setRetryPolicy(new DefaultRetryPolicy(15000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    requestQueue.add(request);

当我调试时,我将所有值都设为 null

谁能帮帮我

【问题讨论】:

  • 它不打印任何东西,如果我调试响应显示所有值 null
  • 检查您收到的响应代码...
  • 首先测试运行你在邮递员中发送的url和数据。那么如果它得到你想要的结果呢?如果是,则检查代码中的错误。你的邮递员回复成功了吗?
  • 是的,如果我运行 url,响应就会正确。我已经在下面发布了问题的答案。

标签: java android json api android-volley


【解决方案1】:

想回答我自己的问题,也许有人可以通过这个得到帮助......

我使用 jsonschema2pojo 创建了我的模型类,我必须选择 JSON 和 GSON(我忘了选择)。

如果您比较上面和下面发布的模型类,您可以看到差异

public class ModelConnection {

    @SerializedName("Data")@Expose
    private List < Datum > data = new ArrayList < Datum > ();@SerializedName("Code")@Expose
    private Integer code;@SerializedName("Message")@Expose
    private Object message;

    private Map < String,
    Object > additionalProperties = new HashMap < String,
    Object > ();

    /**
     *
     * @return
     *     The data
     */
    public List < Datum > getData() {
        return data;
    }

    /**
     *
     * @param data
     *     The Data
     */
    public void setData(List < Datum > data) {
        this.data = data;
    }

    /**
     *
     * @return
     *     The code
     */
    public Integer getCode() {
        return code;
    }

    /**
     *
     * @param code
     *     The Code
     */
    public void setCode(Integer code) {
        this.code = code;
    }

    /**
     *
     * @return
     *     The message
     */
    public Object getMessage() {
        return message;
    }

    /**
     *
     * @param message
     *     The Message
     */
    public void setMessage(Object message) {
        this.message = message;
    }

    public Map < String,
    Object > getAdditionalProperties() {
        return this.additionalProperties;
    }

    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    public class Datum implements Serializable {

        @SerializedName("UserId")@Expose
        private Integer userID;@SerializedName("FirstName")@Expose
        private String firstName;@SerializedName("LastName")@Expose
        private String lastName;@SerializedName("Title")@Expose
        private String title;@SerializedName("Organization")@Expose
        private String organization;@SerializedName("Industry")@Expose
        private String industry;@SerializedName("Location")@Expose
        private String location;@SerializedName("ProfileSummary")@Expose
        private String profileSummary;@SerializedName("ImagePath")@Expose
        private String imagePath;@SerializedName("Interests")@Expose
        private ArrayList < Interest > interest = new ArrayList < Interest > ();

        private Map < String,
        Object > additionalProperties = new HashMap < String,
        Object > ();

        /**
         *
         * @return
         *     The userID
         */
        public Integer getUserID() {
            return userID;
        }

        /**
         *
         * @param userID
         *     The UserID
         */
        public void setUserID(Integer userID) {
            this.userID = userID;
        }

        /**
         *
         * @return
         *     The firstName
         */
        public String getFirstName() {
            return firstName;
        }

        /**
         *
         * @param firstName
         *     The FirstName
         */
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        /**
         *
         * @return
         *     The lastName
         */
        public String getLastName() {
            return lastName;
        }

        /**
         *
         * @param lastName
         *     The LastName
         */
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        /**
         *
         * @return
         *     The title
         */
        public String getTitle() {
            return title;
        }

        /**
         *
         * @param title
         *     The Title
         */
        public void setTitle(String title) {
            this.title = title;
        }

        /**
         *
         * @return
         *     The organization
         */
        public String getOrganization() {
            return organization;
        }

        /**
         *
         * @param organization
         *     The Organization
         */
        public void setOrganization(String organization) {
            this.organization = organization;
        }

        /**
         *
         * @return
         *     The industry
         */
        public String getIndustry() {
            return industry;
        }

        /**
         *
         * @param industry
         *     The Industry
         */
        public void setIndustry(String industry) {
            this.industry = industry;
        }

        /**
         *
         * @return
         *     The location
         */
        public String getLocation() {
            return location;
        }

        /**
         *
         * @param location
         *     The Location
         */
        public void setLocation(String location) {
            this.location = location;
        }

        /**
         *
         * @return
         *     The profileSummary
         */
        public String getProfileSummary() {
            return profileSummary;
        }

        /**
         *
         * @param profileSummary
         *     The ProfileSummary
         */
        public void setProfileSummary(String profileSummary) {
            this.profileSummary = profileSummary;
        }

        /**
         *
         * @return
         *     The imagePath
         */
        public String getImagePath() {
            return imagePath;
        }

        /**
         *
         * @param imagePath
         *     The ImagePath
         */
        public void setImagePath(String imagePath) {
            this.imagePath = imagePath;
        }

        /**
         *
         * @return
         *     The interests
         */
        public ArrayList < Interest > getInterest() {
            return interest;
        }

        /**
         *
         * @param interests
         *     The Interests
         */
        public void setInterest(ArrayList < Interest > interests) {
            this.interest = interests;
        }

        public Map < String,
        Object > getAdditionalProperties() {
            return this.additionalProperties;
        }

        public void setAdditionalProperty(String name, Object value) {
            this.additionalProperties.put(name, value);
        }

    }
    public class Interest {

        @SerializedName("Name")@Expose
        private String name;

        /**
         *
         * @return
         * The name
         */
        public String getName() {
            return name;
        }

        /**
         *
         * @param name
         * The Name
         */
        public void setName(String name) {
            this.name = name;
        }

    }

}

可能是因为对象没有正确序列化,所以 GSON 无法正确解析 JSON 字符串。

非常欢迎对上述假设提出其他建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2015-03-18
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    相关资源
    最近更新 更多