2015-12-14 73 views
-2

我有一個像這樣的json對象,我在我的Fragment中獲得了這個響應。解析json對象在android中使用gson

JSON

{ 
    "data":{ 
     "categories":[ 
     { 
      "id":"d5c4eedf-093e-422f-8335-6c6376ca3ccb", 
      "schedule_m_id":1, 
      "title_en":"Bakery Products", 
      "title_fr":"Produits de boulangerie", 
      "subtitle_en":"Bread, Cakes, Cookies, Crackers, Pies", 
      "subtitle_fr":"Pain, gateaux, biscuits, craquelins, tartes", 
      "created_at":"2015-03-04 15:39:44", 
      "updated_at":"2015-03-04 15:39:44" 
     }, 
     { 
      "id":"6d1d4945-9910-40ae-82a8-3fe4137c24c2", 
      "schedule_m_id":2, 
      "title_en":"Beverages", 
      "title_fr":"Boissons", 
      "subtitle_en":"Soft Drinks, Coffee, Tea, Cocoa", 
      "subtitle_fr":"Boissons gazeuses, café, thé, cacao", 
      "created_at":"2015-03-04 15:39:44", 
      "updated_at":"2015-03-04 15:39:44" 
     } 
     ] 
    }, 
    "result":"success" 
} 

和我的類別類是這樣的:

public class Categories { 
    private int id; 
    private String title_en; 
    private String title_fr; 
    private int schedule_m_id; 
    private String subtitle_en; 

    public int getId() { 
     return id; 
    } 

    public void setId(int id) { 
     this.id = id; 
    } 

    public String getTitle_en() { 
     return title_en; 
    } 

    public void setTitle_en(String title_en) { 
     this.title_en = title_en; 
    } 

    public String getTitle_fr() { 
     return title_fr; 
    } 

    public void setTitle_fr(String title_fr) { 
     this.title_fr = title_fr; 
    } 

    public int getSchedule_m_id() { 
     return schedule_m_id; 
    } 

    public void setSchedule_m_id(int schedule_m_id) { 
     this.schedule_m_id = schedule_m_id; 
    } 

    public String getSubtitle_en() { 
     return subtitle_en; 
    } 

    public void setSubtitle_en(String subtitle_en) { 
     this.subtitle_en = subtitle_en; 
    } 

} 

在我的片段如何可以解析此JSON對象。我需要創建一個類型爲「Categories」的ArrayList。我需要這個類別對象列表來製作一個自定義的適配器。任何一個人都可以幫助我。

JSONObject jsonObject = (JSONObject) response; 
JSONObject dataProject = jsonObject.getJSONObject("data"); 
JSONArray products = dataProject.getJSONArray("categories"); 
Gson gson = new Gson(); 
Categories categories = new Categories(); 
ArrayList<Categories> items = new ArrayList<Categories>(); 
int productCount = products.length(); 

for (int i = 0; i < productCount; i++) { 
    categories = gson.fromJson(products.get(i), Categories.class); 
    items.add(categories); 
} 

```

+0

對不起,這是一個錯誤。 nw看看它 – user2480902

+0

http://stackoverflow.com/questions/16416965/nullpointerexception-json-parsing-in-java-using-gson – rafid059

+0

@RafiduzzamanSonnet是什麼讓你認爲OP是越來越NPE? – azurefrog

回答

0

我張貼類GSON凌空工作可能有助於你....

第一步。解析你的json數據使用「www.jsonschema2pojo.org/」並生成pojo類。在您的項目中複製具有相同名稱的類。

Step2。只要創建一個GsonRequest類如下(從https://developer.android.com/training/volley/request-custom.html拍攝)

public class GsonRequest<T> extends Request<T> { 
private final Gson gson = new Gson(); 
private final Class<T> clazz; 
private final Map<String, String> headers; 
private final Listener<T> listener; 

/** 
* Make a GET request and return a parsed object from JSON. 
* 
* @param url URL of the request to make 
* @param clazz Relevant class object, for Gson's reflection 
* @param headers Map of request headers 
*/ 
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers, 
     Listener<T> listener, ErrorListener errorListener) { 
    super(Method.GET, url, errorListener); 
    this.clazz = clazz; 
    this.headers = headers; 
    this.listener = listener; 
} 

@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
    return headers != null ? headers : super.getHeaders(); 
} 

@Override 
protected void deliverResponse(T response) { 
    listener.onResponse(response); 
} 

@Override 
protected Response<T> parseNetworkResponse(NetworkResponse response) { 
    try { 
     String json = new String(
       response.data, 
       HttpHeaderParser.parseCharset(response.headers)); 
     return Response.success(
       gson.fromJson(json, clazz), 
       HttpHeaderParser.parseCacheHeaders(response)); 
    } catch (UnsupportedEncodingException e) { 
     return Response.error(new ParseError(e)); 
    } catch (JsonSyntaxException e) { 
     return Response.error(new ParseError(e)); 
    } 
} 

Step3.Now在主要活動只是用這種「GsonRequest」級這樣的:

mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 

    GsonRequest<MyPojoClass> gsonRequest = new GsonRequest<MyPojoClass>(
      Request.Method.GET, 
      apiurl, 
      MyPojoClass.class, 
      mySuccessListener(), 
      myErrorListener()); 

    //Add below these code lines for "Retry" data fetching from api 

    gsonRequest.setRetryPolicy(new DefaultRetryPolicy(
      5000, 
      DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
      DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 
    mRequestQueue.add(gsonRequest); 
} 

private Response.Listener<MyPojoClass> mySuccessListener() { 
    return new Response.Listener<CustomRequest>() { 
     @Override 
     public void onResponse(MyPojoClass pRequest) { 
      //do something 
     } 
    }; 
} 

private Response.ErrorListener myErrorListener() { 
    return new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError volleyError) { 
      System.out.println(volleyError.getMessage().toString()); 
     } 
    }; 
}