2017-04-24 92 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; 
      }