2015-02-23 59 views
0

我想解析API:http://api.devnews.today,這是有效的JSON在這裏驗證:http://jsonlint.com/和在這裏的網絡前端解析:http://devnews.todayVolley org.json.JSONException當解析有效的JSON

我正在構建一個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 
+0

的反應似乎是JSONArray沒有的JSONObject 。因此,我相信,例外。 – harism 2015-02-23 19:13:29

回答

2

是JSONArray不JSONObject的。

可以使用(與GSON和截擊爲例):

....

 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; 
    } 
}