-2

I can parse my json file with gson

private void fetchContacts() {
    JsonArrayRequest request = new JsonArrayRequest(URL,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    if (response == null) {
                        Toast.makeText(getApplicationContext(), "Couldn't fetch the contacts! Pleas try again.", Toast.LENGTH_LONG).show();
                        return;
                    }

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

                    // adding contacts to contacts list
                    contactList.clear();
                    contactList.addAll(items);

                    // refreshing recycler view
                    mAdapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // error in getting json
            Log.e(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    MyApplication.getInstance().addToRequestQueue(request);
}

contact.java

public class Contact {
    String name;
    String image;
    String phone;

    public Contact() {
    }

    public String getName() {
        return name;
    }

    public String getImage() {
        return image;
    }

    public String getPhone() {
        return phone;
    }
}

my first json:

[{
            "name": "Tom Hardy",
            "image": "https://api.androidhive.info/json/images/tom_hardy.jpg",
            "phone": "(541) 754-3010"
        },
        {
            "name": "Johnny Depp",
            "image": "https://api.androidhive.info/json/images/johnny.jpg",
            "phone": "(452) 839-1210"
        }
    ]

second json

{ group:
    [{
            "name": "Tom Hardy",
            "image": "https://api.androidhive.info/json/images/tom_hardy.jpg",
            "phone": "(541) 754-3010"
        },
        {
            "name": "Johnny Depp",
            "image": "https://api.androidhive.info/json/images/johnny.jpg",
            "phone": "(452) 839-1210"
        }
    ]
}

I can parse first json file with gson but I can't parse second json file with gson

I can parse first json file with gson but I can't parse second json file with gson

when I try to parse this json it gives me this error

"of type org.json.JSONObject cannot be converted to JSONArray" How can I parse this json file with gson

enter image description here

EagleH
  • 107
  • 2
  • 8

2 Answers2

1

First, add gson dependency

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

Then better use StringRequest,

 StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response)
            {
                try 
                {
                   // convert the response to Object 
                    Object json_response = new JSONTokener(response).nextValue();

                    //checking if the response is array or object
                    if(json_response instanceof JSONArray)
                    {

                    }
                    else 
                    {
                       // this is how you convert to Gson 
                       String json = new Gson().toJson(json_response);
                    }
                } catch (JSONException e) 
                {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        requestQueue.add(stringRequest);

The error you are getting is because the response is in JSONArray form and you are trying to parse it as a JSONObject

The 2nd json is JSONObject and your request is JsonArrayRequest. Check the code below

 JsonObjectRequest request = new JsonObjectRequest(URL,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (response == null) {
                    Toast.makeText(getApplicationContext(), "Couldn't fetch the contacts! Pleas try again.", Toast.LENGTH_LONG).show();
                    return;
                }
                JSONArray jsonArray = response.getJSONArray("group");
                for(int i = 0 ; i < jsonArray.length() ; i++)
                {
                    // get the jsonObject and perform your task
                }

            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        // error in getting json
        Log.e(TAG, "Error: " + error.getMessage());
        Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

Change your code to this

JsonObjectRequest request = new JsonObjectRequest(URL,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) 
            {
                if (response == null) 
                {
                    Toast.makeText(getApplicationContext(), "Couldn't fetch the contacts! Pleas try again.", Toast.LENGTH_LONG).show();
                    return;
                }
                    try
                    {                           
                        JSONArray jsonArray = response.getJSONArray("group");
                        for(int i = 0 ; i < jsonArray.length() ; i++)
                        {
                            // get the jsonObject and perform your task
                        }
                    }
                    catch(JSONException e)
                    {
                        e.printStackTrace();
                    }
             }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        // error in getting json
        Log.e(TAG, "Error: " + error.getMessage());
        Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
    }
});
Aan
  • 289
  • 5
  • 15
0

How to Parse JSON Array with Gson

You can refer above link also. I don't have point to make a comment so posting this as an answer

Create one model named Random.class

public ArrayList<Group> getGroup() {
    return group;
}

public void setGroup(ArrayList<Group> group) {
    this.group = group;
}

@SerializedName("group")
private ArrayList<Group> group;

Create another model class named Group:

public class Group {
@SerializedName("name")
@Expose
private String name;
@SerializedName("image")
@Expose
private String image;
@SerializedName("phone")
@Expose
private String phone;

public String getName() {
    return name;
}

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

public String getImage() {
    return image;
}

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

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}
}

And then you can parse like below:

Random items = new Gson().fromJson(response.toString(), new TypeToken() { }.getType());

    Log.d("safajfjafja", ""+ items.getGroup().get(0).getName());