Android Model for JSON parsing shows ClassCastException: com.google.gson.JsonObject can not be casted to com.google.gson.JsonArray

I am fairly new to Android development and I am creating an app that requires me to consume the Zomato Rest API. I am using the Koush ION library https://github.com/koush/ion for sending the http request and receiving a response. For using this library, I simply create a model java class with the keys as java instance variables and call this line of code.

     Ion.with(getActivity())
                    .load("https://developers.zomato.com/api/v2.1/geocode?lat=25.12819&lon=55.22724")
                    .setHeader("user-key",my-user-key)
                    .asJsonArray()
                    .setCallback(new FutureCallback<JsonArray>() {
                        @Override
                        public void onCompleted(Exception e, JsonArray result) {
                            if (e != null) {
                                Log.d("FoodFragment", "Error loading food"+e.toString());
                                Toast.makeText(getActivity(), "error loading food", Toast.LENGTH_LONG).show();
                                return;
                            }
                            else{
                                Log.d("FoodFragment", "Size= " + result.size() + "; " + result.toString());
                                sTrips = (List<RestaurantsZomato>) new Gson().fromJson(result.toString(), new TypeToken<List<RestaurantsZomato>>() {

                                }.getType());
                                adapter = new RestaurantAdapter(sTrips);
                                recyclerView.setAdapter(adapter);
                                mSwipeRefreshLayout.setRefreshing(false);
                                ((RestaurantAdapter) adapter).setOnItemClickListener(new RestaurantAdapter.MyClickListener() {
                                    @Override
                                    public void onItemClick(int position, View v) {
                                        Toast.makeText(getActivity(), "Item Clicked", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        }
                    });
        }

As per the Zomato API documentation, the response will look something like this -

{"nearby_restaurants": {
"1": {
  "restaurant": {

  }
},
"2": {
  "restaurant": {
  }
},
"3": {
  "restaurant": {

  }
},
"4": {
  "restaurant": {

  }
},
"5": {
  "restaurant": {

  }
},
"6": {
  "restaurant": {

  }
},
"7": {

  }
},
"8": {
  "restaurant": {

  }
},
"9": {
  "restaurant": {

  }
}

And my RestaurantZomato class looks like this -

    public class RestaurantsZomato {
            public NearbyRestaurants nearby_restaurants;
            public static class NearbyRestaurants {
                   public List<RestaurantDetails> restaurant;
     }}

And RestaurantDetails class has everything inside the "restaurant" tag. My question how to represent "1", "2", "3" etc that is present in the JsonResponse in my Model class.

I'm sorry if this question is stupid. As I said I'm new to Android development and any resources that point me in the right direction will be much appreciated!

Upvotes: 0

Views: 712

Answers (3)

Nguyễn Trung Hiếu
Nguyễn Trung Hiếu

Reputation: 2032

public List< RestaurantDetails> restaurant; return Array

public RestaurantDetails restaurant; return Object

Your API return Object. Not return Array

Try this!!

public class RestaurantsZomato {
        public NearbyRestaurants nearby_restaurants;
        public static class NearbyRestaurants {
               public RestaurantDetails restaurant;
 }}

Update

Your Json String return JsonObject. You must use JsonObject

Ion.with(context)
.load("https://developers.zomato.com/api/v2.1/geocode?lat=25.12819&lon=55.22724")
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
    // do stuff with the result or error
}
 });

Upvotes: 0

michoprogrammer
michoprogrammer

Reputation: 1199

In the Json format this

{  
   "nearby_restaurants":{  
      "1":{  
         "restaurant":{  

         }
      },
      "2":{  
         "restaurant":{  

         }
      }
   }
}

corresponds to an object "nearby_restaurants" that contains two objects "1" and "2" that both contains the object "restaurant" with empty value.

You are trying to fill a java List object, but in your Json doesn't exist any list or array!

Look at this and this and you will solve your problem. :-)

EDIT

try this code

JsonObject jsonObject = yourJsonElement.getAsJsonObject();
JsonObject nearby_restaurants = jsonObject.get("nearby_restaurants").getAsJsonObject();
Set<Entry<String, JsonElement>> objects =  nearby_restaurants.entrySet();

Gson gson = new Gson();

for (Entry<String, JsonElement> entry : objects) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

Upvotes: 1

Ragesh Ramesh
Ragesh Ramesh

Reputation: 3520

The problem is that you are receiving a JSON Object inside "nearby_restaurants" and trying to fetch it as a JSONArray. As you can see in the Zomato response there are no [] so there is no json array only objects.

Upvotes: 0

Related Questions