使用类方法时解析JSON android时出错

时间:2016-04-22 05:52:30

标签: android json parsing android-volley

您好我正在使用android Volley从服务器获取JSON,然后将其解析为object。我尝试使用解析JSON响应的方法创建一个类。我的网址例如是:https://hacker-news.firebaseio.com/v0/item/11544988.json?print=pretty

这是我的班级方法(在TopStory.java

public static TopStory fromJson(JSONObject jsonObject) {
        TopStory topStory = new TopStory();

        // Deserialize json into object fields
        try {
            topStory.id = jsonObject.getInt(Constant.TAG_ID);
            topStory.title = jsonObject.getString(Constant.TAG_TITLE);
            topStory.author = jsonObject.getString(Constant.TAG_AUTHOR);
            topStory.timestamp = jsonObject.getInt(Constant.TAG_TIMESTAMP);
            topStory.url=jsonObject.getString(Constant.TAG_URL);

        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
        // Return new object
        return topStory;
    }
MainActivity中的

。我使用Volley来获取响应并使用类方法将其解析为object。我可以得到响应(可以显示Toast)但在解析时遇到错误:java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.vic.hackernew.Model.TopStory.getAuthor()' on a null object reference。任何帮助都非常感激。感谢。

private void getTopStoryDetail(RequestQueue requestQueue, String topStoryUrl) {

        progressBar.setVisibility(View.VISIBLE);
        CustomJsonObjectRequest jsonObjectRequest = new CustomJsonObjectRequest(Request.Method.GET,topStoryUrl,null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject respond) {
                        progressBar.setVisibility(View.GONE);

                        Toast.makeText(getApplicationContext(),respond.toString(), Toast.LENGTH_LONG).show();

                        TopStory topStory = TopStory.fromJson(respond);

                        topStories.add(topStory);

                        Toast.makeText(getApplicationContext(), topStory.getAuthor(), Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                        progressBar.setVisibility(View.GONE);
                    }
                });
        //Adding request to the queue
        requestQueue.add(jsonObjectRequest);
    }

我的整个TopStory.java

package com.vic.hackernew.Model;

import android.widget.Toast;

import com.vic.hackernew.Utils.Constant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.sql.Array;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by vic on 21-Apr-16.
 */
public class TopStory {
    private int id;
    private String title;
    private String author;
    private int score;
    private int[] kids;
    private int timestamp;
    private String url;

    public TopStory() {
    }

    public TopStory(int id, String title, String author, int point, int timestamp,String url) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.score = point;
        this.timestamp = timestamp;
        this.url = url;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public int getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(int timestamp) {
        this.timestamp = timestamp;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int[] getKids() {
        return kids;
    }

    public void setKids(int[] kids) {
        this.kids = kids;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    // Decodes business json into business model object
    public static TopStory fromJson(JSONObject jsonObject) {
        TopStory topStory = new TopStory();

        // Deserialize json into object fields
        try {
            topStory.id = jsonObject.getInt(Constant.TAG_ID);
            topStory.title = jsonObject.getString(Constant.TAG_TITLE);
            topStory.author = jsonObject.getString(Constant.TAG_AUTHOR);
            topStory.timestamp = jsonObject.getInt(Constant.TAG_TIMESTAMP);
            topStory.url=jsonObject.getString(Constant.TAG_URL);

        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
        // Return new object
        return topStory;
    }

我的Constanst.java

public class Constant {
    public static String TAG_ID = "id";
    public static String TAG_TITLE = "title";
    public static String TAG_AUTHOR = "by";
    public static String TAG_KIDS = "kids";
    public static String TAG_SCORE = "point";
    public static String TAG_TIMESTAMP = "timestamp";
    public static String TAG_URL = "url";

    public static String TAG_CONTENT = "content";
    public static String TAG_BASE_URL = "https://hacker-news.firebaseio.com/v0/";
    public static String TAG_TOPSTORIES_URL = "topstories.json";
}

1 个答案:

答案 0 :(得分:0)

只需将此行粘贴到解析

topStory.author = jsonObject.optString(Constant.TAG_AUTHOR);

而不是

topStory.author = jsonObject.getString(Constant.TAG_AUTHOR);

如果这样可以解决您的问题,那么问题就在您对某个项目网址的回复中。

所以看着json你正在接受它是

{

    "by": "maibaum",
    "descendants": ​156,
    "id": ​11544988,
    "kids": 

    [
        ​11545261,
        ​11546393,
        ​11545187,
        ​11546084,
        ​11545168,
        ​11546078,
        ​11545846,
        ​11546650,
        ​11545285,
        ​11545262,
        ​11545178,
        ​11546996,
        ​11545394,
        ​11546690,
        ​11546275,
        ​11545336,
        ​11545515,
        ​11545127,
        ​11546000,
        ​11546043,
        ​11546842,
        ​11546025,
        ​11546221,
        ​11545281,
        ​11545142,
        ​11546502,
        ​11546215,
        ​11546070,
        ​11546257,
        ​11546258,
        ​11545195
    ],
    "score": ​238,
    "time": ​1461269223,
    "title": "FBI Paid More Than $1M to Hack San Bernardino iPhone",
    "type": "story",
    "url": "http://www.wsj.com/articles/comey-fbi-paid-more-than-1-million-to-hack-san-bernardino-iphone-1461266641"

}

如果你调查它,你将找不到任何作者字段。这就是你得到null的原因。此外,如果是作者,我在此回复中看到“by”,那么您应该将Constant.Author更改为“by”而不是“author”,这可能会解决您的问题。 我希望它会有所帮助。