2016-05-26 73 views
0

凌空我有這裏的情況 在服務器端的一些JSON代碼...這裏是JSON的一部分解析JSONArray與Android的

{ 
 
"status":"ok", 
 
"count":10, 
 
"count_total":88, 
 
"pages":9, 
 
"posts": 
 
[{ 
 
"id":1530, 
 
"type":"post", 
 
"slug":"slug", 
 
""url":"url", 
 
"status":"publish", 
 
"title":"title", 
 
"title_plain":"sth", 
 
"content":"some content", 
 
"modified":"2016-05-22 20:21:47", 
 
"categories":[{"blah":"blah"}] 
 
}] 
 
}

我想要的「內容」在「posts」數組下面,凌空不會讓我在jsonobject裏面使用jsonarray。

這裏是我的代碼的一部分:

JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, url, new 
 

 
Response.Listener<JSONObject>() { 
 

 
     @Override 
 
     public void onResponse(JSONObject response) { 
 
      try { 
 
       JSONObject obj = response.getJSONObject("posts"); 
 
      
 
       
 
      } 
 
      JSONcatch (JSONException e) { 
 
       
 
       e.printStackTrace(); 
 
      } 
 
     } 
 
    },null);

遺憾的片斷我不能插入我的代碼...

TNX

+0

帖子是數組,而不是一個對象。使用相應的方法爲數組,它將工作 –

+1

可能重複[如何解析JSON在Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) –

回答

2

那是一個錯字或其他東西,但你的JSON無效,你在這裏有兩個雙引號""url":"url"。只要刪除一個。

只是這樣做:

JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, url, new 

      Response.Listener<JSONObject>() { 

       @Override 
       public void onResponse(JSONObject response) { 
        try { 
         JSONArray obj = response.getJSONArray("posts"); 

         for (int i = 0; i < obj.length(); i++) { 

          JSONObject jsonObject = obj.getJSONObject(i); 

          int id = jsonObject.getInt("id"); 

          String type = jsonObject.getString("type"); 

          // retrieve the values like this so on.. 

         } 

        } 
        catch (JSONException e) { 

         e.printStackTrace(); 
        } 
       } 
      },null); 
+0

tnx for答案...我讓這個JSON只是例如我有我的網站上的JSON發電機插件,它生成正確的JSON –

+0

我的檢查它PLZ –

+0

檢查我的編輯,然後讓我知道..! –

3

首先創建模型:

public class CategoryModel 
{ 
    public String blah; 
} 

public class PostModel 
{ 
    public int id; 
    public String type; 
    public String slug; 
    public String url; 
    public String status; 
    public String title; 
    public String title_plain; 
    public String content; 
    public String modified; 
    public List<CategoryModel> categories; 
} 

public class PostsModel 
{ 
    public String status; 
    public int count; 
    public int count_total; 
    public int pages; 
    public List<PostModel> posts; 
} 

然後使用GSON;

在gradle這個

compile 'com.google.code.gson:gson:2.4' 

然後在代碼中得到你的對象:

JSONObject json; 
Gson gson = new Gson(); 
      try { 
       json = new JSONObject(yourJsonString) 
       PostsModel result = gson.fromJson(json, PostsModel.class); 
       return result; // this is your deserialized response object 
      }catch(Exception e){ 
      } 

亂射: 在App類:

private VolleyServiceSingleton mVolleySingleton; 
private RequestQueue mVolleyApiClient; 

上創建:

mVolleySingleton = VolleyServiceSingleton.getInstance(); 
mVolleyApiClient = mVolleySingleton.gerRequestQueue(); 

字符串請求:

class VolleyStringRequest extends StringRequest 
    { 
     private Map<String, String> mParams; 
     public VolleyStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener, Map<String, String> requestParams) { 
      super(method, url, listener, errorListener); 
      mParams = requestParams; 
      afterRequestErrorRunnable = null; 
      Log.e("Request",url); 
     } 

     @Override 
     protected VolleyError parseNetworkError(VolleyError volleyError) { 
      if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){ 
       try { 
        Log.e("errorResponse", new String(volleyError.networkResponse.data, "utf-8")); 
       }catch(Exception e){ 

       } 


      } 
      return super.parseNetworkError(volleyError); 
     } 

     @Override 
     public RetryPolicy getRetryPolicy() { 
      DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(
        TIMEOUT_IN_MILLISECONDS, 
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); 
      return retryPolicy; 
     } 

     @Override 
     public Map getHeaders() throws AuthFailureError { 
      Map headers = new HashMap(); 
      headers.put("Accept-Charset","utf-8"); 
      //headers.put("Accept", RITEAID_HTTP_CONTENT_TYPE); 
      return headers; 
     } 

     @Override 
     public Map<String, String> getParams() { 
      return mParams; 
     } 

    } 

和請求(必須定製):

HashMap<String, String> paramMap = new HashMap<String, String>(); 
     paramMap.put("sign_in_username_email", Utils.nullToStringOrString(username)); 
     paramMap.put("sign_in_password", password != null ? Utils.passwordConvert(password) : ""); 
     paramMap.put("key", Constants.API_KEY); 

     mResponseHandler = getResponseHandler(requestUrl, positiveResponseFunc, inClass); 
     VolleyStringRequest request = new VolleyStringRequest(Request.Method.POST, getFinalUrl(requestUrl, null), getResponseHandler(requestUrl, positiveResponseFunc, inClass), createErrorListener(context, progress), paramMap); 
     request.setRetryPolicy(mRetryPolicy); 
     request.setTag(REQUEST_TAG); 
     mVolleyApiClient.add(request); 
+0

tnx斯捷潘我該如何將它轉換爲排球庫?我必須從互聯網上獲取json代碼 –

+0

tnx Stepan如何將其轉換爲排球庫?我必須從互聯網上獲取json代碼 –

+0

在您的appclass中創建VolleySingleton,然後獲取它的實例,然後創建將調用的類,然後響應您將獲得json字符串,反序列化有時也是艱鉅的任務,因此反序列化也必須在異步任務中,你可以在你的類中創建接口並在活動中實現它們,並且當數據反序列化時,你可以運行接口並準備好數據,並在你的活動中捕獲它們 –