1

Main Activity Code fragment ... i have tried responce.getObject but it didnot work...

JsonArrayRequest request = new JsonArrayRequest( Request.Method.GET,
               URL,
                null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response == null) {
                            Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show();
                            return;
                        }
                        List<Person> persons = new Gson().fromJson(response.toString(), new TypeToken<List<Person>>() {
                        }.getType());

                        // adding persons to cart list
                        cartList.clear();
                        cartList.addAll(persons);

Myjson file

{
  "code": 1200,
  "message": "Data Retrieved",
  "data": [
    {
      "id": 1,
      "name": "Vangipurapu Venkata Sai Laxman",
      "skills": "Cricketer, Batsman",
      "image": "https://qph.ec.quoracdn.net/main-qimg-4f5029c4319b41270f5643d461979645-c"
    },
    {
      "id": 2,
      "name": "Himesh Reshammiya",
      "skills": "music director, singer, producer, lyricist, distributor and actor",
      "image": "https://starsunfolded-1ygkv60km.netdna-ssl.com/wp-content/uploads/2016/01/Himesh-Reshammiya-nasal-singing.jpg"
    }
]
}

How to identify the object "data" and access all the array.

3 Answers3

0

You need to parse the entire JSON response, not just the "data" property. The GSON file used to parse it will probably look something like this:

public class MyJsonResponse {
    @SerializedName("code")
    private int code;
    @SerializedName("message")
    private String message;
    @SerializedName("data")
    private List<Person> data;
}

Then you can get the data field from your parsed response.

0

You can use this link to convert you json response to POJO classes. For your current response it would be like, It has also implemented Parcelable below is the code:

JsonResponse.java

public class JsonResponse implements Parcelable
{

@SerializedName("code")
@Expose
private Integer code;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private List<Datum> data = null;
public final static Parcelable.Creator<JsonResponse> CREATOR = new Creator<JsonResponse>() {


@SuppressWarnings({
"unchecked"
})
public JsonResponse createFromParcel(Parcel in) {
return new JsonResponse(in);
}

public JsonResponse[] newArray(int size) {
return (new JsonResponse[size]);
}

}
;

protected JsonResponse(Parcel in) {
this.code = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.message = ((String) in.readValue((String.class.getClassLoader())));
in.readList(this.data, (com.heyoe_chat.model.Datum.class.getClassLoader()));
}

public JsonResponse() {
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public List<Datum> getData() {
return data;
}

public void setData(List<Datum> data) {
this.data = data;
}

public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(code);
dest.writeValue(message);
dest.writeList(data);
}

public int describeContents() {
return 0;
}

}

Datum.java for objects in array.

public class Datum implements Parcelable
{

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("skills")
@Expose
private String skills;
@SerializedName("image")
@Expose
private String image;
public final static Parcelable.Creator<Datum> CREATOR = new Creator<Datum>() {


@SuppressWarnings({
"unchecked"
})
public Datum createFromParcel(Parcel in) {
return new Datum(in);
}

public Datum[] newArray(int size) {
return (new Datum[size]);
}

}
;

protected Datum(Parcel in) {
this.id = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.name = ((String) in.readValue((String.class.getClassLoader())));
this.skills = ((String) in.readValue((String.class.getClassLoader())));
this.image = ((String) in.readValue((String.class.getClassLoader())));
}

public Datum() {
}

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSkills() {
return skills;
}

public void setSkills(String skills) {
this.skills = skills;
}

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(id);
dest.writeValue(name);
dest.writeValue(skills);
dest.writeValue(image);
}

public int describeContents() {
return 0;
}

}
Aseem Sharma
  • 1,673
  • 12
  • 19
0

First of all you cannot use JsonArrayRequest in this case. This is because your Myjson file does not have an array at root but rather an object.You should be using JsonObjectRequest instead.

So this is how your code should look:

JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            URL,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (response == null) {
                        Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Person persons = new Gson().fromJson(response.toString(), new TypeToken<Person>() {
                    }.getType());

                    // adding persons to cart list
                    cartList.clear();
                    cartList.add(persons);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("error", error.toString());
                }
    });

Remember to change

 List<Person> persons = new Gson().fromJson(response.toString(), new TypeToken<List<Person>>() {
                    }.getType());

to

Person persons = new Gson().fromJson(response.toString(), new TypeToken<Person>() {
                }.getType());

This is because of the same reason as above: you are getting a json object not a json array.

Now, the way Gson works is that it needs a class to 'map' the received Json to. Therefore you have to create a class. Looking at your Json, this is simple implementation of your Person class.

public class Person {
private int code;
private String message;
private List<Data> data;

public int getCode() {
    return code;
}

public String getMessage() {
    return message;
}

public List<Data> getData() {
    return data;
}

public class Data {
    private int id;
    private String name;
    private String skills;
    private String image;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getSkills() {
        return skills;
    }

    public String getImage() {
        return image;
    }
}}

And this is how you access the data array and its objects.

for (int i = 0; i < cartList.size(); i++) {
                        for (Person.Data data : cartList.get(i).getData()) {
                            Log.d("TAG", "Name: " + data.getName() + ", Skill: " + data.getSkills() + ", Image: " + data.getImage() + ", id: " + data.getId());
                        }
                    }

Here i am printing data in the Logcat. Make sure to do this in the onResponse() block.

And this is how the complete code looks like:

        requestQueue = Volley.newRequestQueue(this);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            URL,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (response == null) {
                        Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Person persons = new Gson().fromJson(response.toString(), new TypeToken<Person>() {
                    }.getType());

                    // adding persons to cart list
                    cartList.clear();
                    cartList.add(persons);

                    for (int i = 0; i < cartList.size(); i++) {
                        for (Person.Data data : cartList.get(i).getData()) {
                            Log.d("TAG", "Name: " + data.getName() + ", Skill: " + data.getSkills() + ", Image: " + data.getImage() + ", id: " + data.getId());
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("error", error.toString());
                }
    });

    requestQueue.add(request);

Hope this helps.

will
  • 399
  • 1
  • 11
  • WOho....You just saved my whole night..Thanks for your explanation :) one more thing.. can u pleasae give me a good link from where i can read more about jsonparsing and all these concepts...Thanks a lot –  Feb 07 '18 at 16:03
  • @satyajitdas You're welcome :) here are some links [link](https://www.androidhive.info/2012/01/android-json-parsing-tutorial/) and for Gson [link](https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/) . And can you please accept my answer, will be of great help :) – will Feb 07 '18 at 17:20