java - 解析有效 JSON 时出现 Volley org.json.JSONException

标签 java android json android-volley

我正在尝试解析 API:http://api.devnews.today ,这是在此处验证的有效 JSON:http://jsonlint.com/并在此处的 Web 前端进行解析:http://devnews.today .

我正在构建一个 Android 客户端来使用 Volley 解析此数据。

下面的代码抛出 Error.Listener,但返回部分预期的 JSON:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RequestQueue queue = Volley.newRequestQueue(this);
        final String url = "http://api.devnews.today";

        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        // display response
                        Log.d("Response", response.toString());
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("Error.Response", error.getMessage());
                    }
                }
        );

        queue.add(getRequest);
    }

错误:

02-23 18:58:26.927  28841-28841/jacob.uk.com.developernews D/Error.Response﹕ org.json.JSONException: Value [{"source":"reddit","score":831,"title":"Lenovo's SuperFish Removal Tool on GitHub","url":"https:\/\/github.com\/lenovo-inc\/superfishremoval"},{"source":"reddit","score":411,"title":"UNIX V5, OpenBSD, Plan 9, FreeBSD, and GNU coreutils implementations of echo.c","url":"https:\/\/gist.github.com\/dchest\/1091803"},{"source":"reddit","score":203,"title":"GCC has built in support for compiling Go","url":"https:\/\/gcc.gnu.org\/gcc-4.6\/changes.html#go"},{"source":"hackernews","score":131,"title":"React Tips and Best Practices","url":"http:\/\/aeflash.com\/2015-02\/react-tips-and-best-practices.html"},{"source":"hackernews","score":115,"title":"Introduction to Facebook's Flux architecture","url":"http:\/\/ryanclark.me\/getting-started-with-flux\/"},{"source":"hackernews","score":112,"title":"Battery power alone can be used to track Android phones","url":"http:\/\/www.bbc.co.uk\/news\/technology-31587621"},{"source":"hackernews","score":109,"title":"Marijuana may be even safer than previously thought, researchers say","url":"http:\/\/www.washingtonpost.com\/blogs\/wonkblog\/wp\/2015\/02\/23\/marijuana-may-be-even-safer-than-previously-thought-researchers-say\/"},{"source":"hackernews","score":85,"title":"On meta-design and algorithmic design systems","url":"http:\/\/runemadsen.com\/blog\/on-meta-design-and-algorithmic-design-systems\/"},{"source":"hackernews","score":84,"title":"Our first building block in tech for tykes: YouTube Kids","url":"http:\/\/googleblog.blogspot.com\/2015\/02\/youtube-kids.html?m=0"},{"source":"hackernews","score":83,"title":"As Office Space Shrinks, So Does Privacy for Workers","url":"http:\/\/www.nytimes.com\/2015\/02\/23\/nyregion\/as-office-space-shrinks-so-does-privacy-for-workers.html?hp&action=click&pgtype=Homepage&module=second-column-region&region=top-news&WT.nav=top-news"},{"source":"hackernews","score":79,"title":"Texas Hold'em Hand Strength, Visualized","url":"http:\/\/chrisbeaumont.org\/holdem_odds\/#8H+QS"},{"source":"hackernews","score":68,"title":"There exists a classical model of the photon after all","url":"https:\/\/www.lightbluetouchpaper.org\/2015\/02\/23\/maxwell\/"},{"source":"hackernews","score":62,"title":"Samba remote execution vulnerability (CVE-2015-0240)","url":"https:\/\/securityblog.redhat.com\/2015\/02\/23\/samba-vulnerability-cve-2015-0240\/"},{"source":"hackernews","score":44,"title":"Stenographer â A full-packet-capture utility","url":"https:\/\/github.com\/google\/stenographer"},{"source":"hackernews","score":40,"title":"How I Wrote an Ultra-Fast DNA Sequence Alignment Algorithm in JavaScript","url":"https:\/\/medium.com\/@keithwhor\/nbeam-how-i-wrote-an-ultra-fast-dna-sequence-alignment-algorithm-in-javascript-c199e936da"},{"source":"reddit","score":23,"title":"Edge Detection in Computer Vision","url":"http:\/\/austingwalters.com\/edge-detection-in-computer-vision\/"},{"source":"hackernews","score":23,"title":"Google Wallet and Softcard","url":"http:\/\/googlecommerce.blogspot.com\/2015\/02\/tap-tap-whos-there-google-wallet-and.html"},{"source":"reddit","score":19,"title":"Bug finding is slow in spite of many eyeballs","url":"http:\/\/daniel.haxx.se\/blog\/2015\/02\/23\/bug-finding-is-slow-in-spite-of-many-eyeballs\/"},{"source":"hackernews","score":19,"title":"Show HN: Just how much is an H1B visa in the software industry worth?","url":"http:\/\/swizec.github.io\/h1b-software-salaries\/#2014-ca-engineer"},{"source":"reddit","score":16,"title":"Exact analysis of Chutes and Ladders in Python","url":"http:\/\/possiblywrong.wordpress.com\/2015\/02\/20\/analysis-of-chutes-and-ladders\/"},{"source":"reddit","score":16,"title":"Triangular numbers mod 2^n","url":"https:\/\/fgiesen.wordpress.com\/2015\/02\/22\/triangular-numbers-mod-2n\/"},{"source":"hackernews","score":14,"title":"Useful Mac","url":"http:\/\/usefulmac.com\/"},{"source":"reddit","score":9,"title":"100-Language Uroboros Quine","url":"https:\/\/github.com\/mame\/quine-relay?100"},{"source":"reddit","score":9,"title":"Have we forgott

最佳答案

JSONArray 不是 JSONObject。

您可以使用(例如 GSON 和 Volley):

...

        JsonArrayRequest myReq = new JsonArrayRequest(
                                                "http://api.devnews.today",
                                                createMyReqSuccessListener(),
                                                createMyReqErrorListener()){
            };
        queue.add(myReq);
   }
    });
}


private Response.Listener<JSONArray> createMyReqSuccessListener() {
    return new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {


            JSONArray array= null;
            try {
             array = response;


                for(int i=1;i < array.length();i++) {

                    Gson gson = new Gson();
                    Devnews contact = gson.fromJson(String.valueOf(array.getJSONObject(i)), Devnews.class);

                    mTvResult.append(contact.getUrl() + " "+contact.getScore() + " " + contact.getSource()+ " "+ contact.getTitle());

                }

                } catch (JSONException e1) {
                e1.printStackTrace();
            }


        }
    };
}


private Response.ErrorListener createMyReqErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTvResult.setText(error.getMessage());
        }
    };
}

DevNews 类是:

public class Devnews {

    @SerializedName("url")
    private String url;

    @SerializedName("title")

    private String title;

    @SerializedName("score")
    private String score;

    @SerializedName("source")
    private String source;

    public String getTitle() {
        return title;
    }

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

    public String getUrl() {
        return url;
    }

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

    public String getScore() {
        return score;
    }

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

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }
}

关于java - 解析有效 JSON 时出现 Volley org.json.JSONException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28681423/

相关文章:

Java 链式/嵌套方法调用

java - 何时选择 @RequestParam 而不是 @PathVariable,反之亦然?

安卓:Facebook 图表 API v1.0

android - 调整 TextView 大小以适合文本(带有 9-patch 背景图像)?

javascript - NodeJS 多站点网络抓取

javascript - React.js 创建一个包含动态行数和可编辑列的表

java - 获取 javaFX 8 中节点的屏幕坐标

Java Web Start - 运行时出现 ClassNotFoundException

java - 使用 GSON 从 JSON 转换,无法将 ArrayList 转换为对象

java - 如何将 TabLayout 与 Recyclerview 同步?