2017-04-24 103 views
0

當我從reddit的JSON API請求數據時,我得到了我的jsonRequestObject如下:解析JSON從reddit的JSON API

[ ] https://www.reddit.com/.json 0x70eb7ea8 NORMAL null 

這是代碼我使用:

public class RedditFront { 
    private static String frontPageURL = "https://www.reddit.com/.json"; 
    private static String jsonResponse = ""; 


    public static void redditFrontAll(final Context context) throws JSONException { 
     Log.d("REDDIT", "got here"); 

     JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, 
       frontPageURL, null, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 
       try { 
        JSONObject data = response.getJSONObject("data"); 
        JSONArray children = data.getJSONArray("children"); 
        for (int i = 0; i < children.length(); i++) { 
         JSONObject topic = children.getJSONObject(i); 

         String author = topic.getString("author"); 
         String imageUrl = topic.getString("thumbnail"); 
         String postTime = topic.getString("created_utc"); 
         String rScore = topic.getString("score"); 
         String title = topic.getString("title"); 
         Log.d("REDDIT_TITLE:", title); 
        } 

       } catch (JSONException e) { 
        e.printStackTrace(); 
        Toast.makeText(context, 
          "Error: " + e.getMessage(), 
          Toast.LENGTH_LONG).show(); 
       } 

      } 
     }, 
       new Response.ErrorListener() { 

        @Override 
        public void onErrorResponse(VolleyError error) { 
         VolleyLog.d(TAG, "Error: " + error.getMessage()); 
         Toast.makeText(context, 
           error.getMessage(), Toast.LENGTH_SHORT).show(); 

        } 
       }); 
     Log.d("JSON:", jsonResponse); 
    } 
} 

我一般不太確定抽球,所以我跟着這個教程。我認爲的JSON代碼是正確的,但我不確定。有人能幫助我嗎?由於

+0

什麼問題添加頁眉這樣嗎?你只是想確認你是否正確地解析了你的文章 –

+0

'有人能幫助我嗎?什麼是問題? –

+0

使用Reddit API,您可以將請求URL插入Web瀏覽器,並在瀏覽器窗口中查看返回的JSON。這對你有幫助嗎? –

回答

0

PLZ在JSON請求類

@Override 
      public Map<String, String> getHeaders() throws AuthFailureError { 
       HashMap<String, String> headers = new HashMap<String, String>(); 
       headers.put("Content-Type", "application/json; charset=utf-8"); 
       return headers; 
      }