在android中使用gson解析json对象

时间:2015-12-14 21:54:15

标签: java android gson

我有一个像这样的json对象,我在片段中得到了这个响应。

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

```

1 个答案:

答案 0 :(得分:0)

我发布了一个与gson volley一起工作的课程可能对你有帮助....

步骤1。要解析您的json数据,请使用&#34; www.jsonschema2pojo.org /&#34;并生成pojo类。复制项目中具有相同名称的类。

第二步。只需创建一个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。现在你的主要活动只使用这个&#34; GsonRequest&#34;这样的课:

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