user445338
user445338

Reputation:

Parse multiple items in JSON into an array

I have a client that retrieves some json from this page. The json content looks like this:

{
  "0": {
    "name": "McDonalds 2",
    "address": "892 West 75th Street, Naperville, IL 60540"
  },
  "1": {
    "name": "McDonalds 1",
    "address": "1298 South Naper Boulevard, Naperville, IL 60540"
  },
  "2": {
    "name": "Burger King 1",
    "address": "2040 Aurora Avenue, Naperville, IL, 60540"
  }
}

I'm having problems parsing it. I always get an exception when trying to parse anything. It's my first time doing json so I might be doing something really bad. This is my code:

public static void parse(String jsonData)
    {
         JSONObject jsonObject = new JSONObject();
         try 
         {
                jsonObject = new JSONObject(jsonData);
         } 
         catch (JSONException e) 
         {
                e.printStackTrace();
         }

         try 
         {
             // exception happens here when trying to access data
             JSONObject name = ((JSONArray)jsonObject.get("0")).getJSONObject(0)
                        .getJSONObject("name");

             JSONObject address = ((JSONArray)jsonObject.get("0")).getJSONObject(0)
                        .getJSONObject("address");

         } catch (JSONException e) {}
    }

How an I retrieve the name and address of each json item to convert it into a restaurant object?

Upvotes: 0

Views: 2003

Answers (1)

Augustus Francis
Augustus Francis

Reputation: 2670

The format of the JSON is wrong. Please refer to this link and the right code is below. You will know what to do.

public static void parse(String jsonData) {
    ArrayList<Restaurant> restaurantList= new ArrayList<Restaurant>();
    JSONObject jsonObject;
    JSONObject jsonRestaurant;

    try {
        jsonObject= new JSONObject(jsonData);
        for(int i=0;i<3;i++) {
            Restaurant restaurant= new Restaurant();
            jsonRestaurant= jsonObject.getJSONObject(Integer.toString(i));
            restaurant.name= jsonRestaurant.getString("name");
            restaurant.address= jsonRestaurant.getString("address");
            restaurantList.add(restaurant);
        }
    }
    catch(JSONException e) {
        e.printStackTrace();
    }
}

Upvotes: 4

Related Questions