-2

i have an json object like this and i am getting this response in my Fragment.

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"
}

and my categories class is like this:

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

}

In my fragment how can i parse this json object. i need to make an ArrayList which type is "Categories". i need this Categories object List to make an custom adapter. Can anybode help me.

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

```

5
  • 1
    The first thing that jumps out at me is that you've defined the id field in Categories as an int, but the json you're getting has some sort of GUID. d5c4eedf-093e-422f-8335-6c6376ca3ccb is not going to parse cleanly into an int field. Commented Dec 14, 2015 at 22:58
  • When I try to run a cut-down version of your code, I'm getting a NumberFormatException when gson tries to parse that field. Commented Dec 14, 2015 at 22:58
  • If I change the type of id to String in the Categories class, I can create a JSONObject using the sample json you provided and your code runs cleanly for me. Try changing the type and let me know if your program is still failing. Commented Dec 14, 2015 at 23:06
  • @azurefrog thanks for your comment. i have change the type of id. but problem with this line categories = gson.fromJson(products.get(i), Categories.class); it's showing that it can not resolve method formjson. Commented Dec 16, 2015 at 14:49
  • Thanks @azurefrog i have solve this problem. Commented Dec 16, 2015 at 15:34

1 Answer 1

0

I posting a class working with gson volley May be Helpful for you....

Step1. For Parsing your json data use "www.jsonschema2pojo.org/" and generate pojo classes. copy classes in your project with same name.

Step2. Just create a GsonRequest Class as follows (taken from 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 in your main Activity just use this "GsonRequest" class like that:

 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());
        }
    };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.