0

I've been searching for a while on how to sort a JSON object like this. It has a lot of attributes but I'm just trying to sort the objects into alphabetical order by "name":

I'm really new to java so you have any information to get started that'll be great!

//update:

So I figured out how to extract the attributes of each restaurant and now I'm trying to implement a comparator to sort the json objects but I'm confused on how to call the comparator and what arg to input

This is the comparator I'm using (got it from the internet)

public class AlphabeticalComparator  implements Comparator<String> {
        public int compare(String obj1, String obj2) {
            if (obj1 == null) {
                return -1;
            }
            if (obj2 == null) {
                return 1;
            }
            if (obj1.equals( obj2 )) {
                return 0;
            }
            return obj1.compareTo(obj2);
        }
    }

I'm also a little confused on how this sorts the objects since it will only return an integer. The json object im trying to sort is below

This is the JSON Object I get in response when I connect to the zomato API

``

{
  "results_found": 10573,
  "results_start": 0,
  "results_shown": 20,
  "restaurants": [
    {
      "restaurant": {
        "R": {
          "res_id": 16795271
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16795271",
        "name": "Craigie On Main", //This is what I want to sort it by
        "url": "https://www.zomato.com/boston/craigie-on-main-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "853 Main St, Cambridge 02139",
          "locality": "Central Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3634820000",
          "longitude": "-71.0985660000",
          "zipcode": "02139",
          "country_id": 216,
          "locality_verbose": "Central Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "European, French",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "342"
        },
        "photos_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16795271",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798941
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798941",
        "name": "O Ya",
        "url": "https://www.zomato.com/boston/o-ya-boston?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "9 East St, Boston 02111",
          "locality": "Leather District",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3513170000",
          "longitude": "-71.0570370000",
          "zipcode": "02111",
          "country_id": 216,
          "locality_verbose": "Leather District, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Japanese, Sushi",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.3",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "192"
        },
        "photos_url": "https://www.zomato.com/boston/o-ya-boston/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/o-ya-boston/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?output-format=webp",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798941",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/o-ya-boston/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798079
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798079",
        "name": "Solea Restaurant and Tapas Bar",
        "url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "388 Moody St, Waltham 02453",
          "locality": "Waltham",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3695490000",
          "longitude": "-71.2370130000",
          "zipcode": "02453",
          "country_id": 216,
          "locality_verbose": "Waltham, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Spanish, Tapas",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "303"
        },
        "photos_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798079",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
"restaurant": {
        "R": {
          "res_id": 16796139
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16796139",
        "name": "Harvest",
        "url": "https://www.zomato.com/boston/harvest-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "44 Brattle St, Cambridge 02138",
          "locality": "Harvard Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3742680000",
          "longitude": "-71.1219960000",
          "zipcode": "02138",
          "country_id": 216,
          "locality_verbose": "Harvard Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "American, Breakfast",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "3.9",
          "rating_text": "Good",
          "rating_color": "9ACD32",
          "votes": "190"
        },
        "photos_url": "https://www.zomato.com/boston/harvest-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/harvest-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16796139",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/harvest-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
2
  • thanks for noticing, I deleted it from the question Commented Dec 9, 2017 at 2:44
  • Like a HashMap, JSON has no concept of key ordering. Aren't you going to parse this JSON into an Object anyway? Commented Dec 9, 2017 at 4:48

2 Answers 2

1

Write a Comparator that orders a pair of JSON objects based on their respective name attributes. Then use that to sort your array of JSON objects; e.g. using Arrays.sort(objects, comparator).

Here is a (more general) example:

You can modify that code to replace the OffersOrder class with your JSON object type (or a custom class) and then implement the comparator to compare objects and return the appropriate value.

Sign up to request clarification or add additional context in comments.

9 Comments

Ok I searched a little bit more and came across this code
That code that you found is not real Java code. If you want to understand how Arrays.sort or Collections.sort work, the javadoc explains it.
OK Ill try to modify it, Thanks!
So I looked at that code and was wondering how I get the names of the restaurants into a list so I can then sort the names?
You don't. Your write your comparator so that it looks at two JSON objects and compares them based on the values of their name attributes.
|
0

I'm only familiar with using Google's gson library which is a bit old. If there are better json parsers available I'm sure somebody can chime in. You'd use it like this to extract the information:

String restaurantName;
JsonElement restaurantJSONElement;
JsonPrimitive restaurantJSONPrimitive;

JsonParser parser = new JsonParser();
// myJSONstring is the raw JSON data
JsonElement parentJSONElement = parser.parse(myJSONstring);
JsonObject parentJSONObject = parentJSONElement.getAsJsonObject();
JsonArray restaurantsJSONArray = (JsonArray) parentJSONObject.get("restaurants");
for(int i=0;i<restaurantsJSONArray.size();i++){
  //get the element
  restaurantJSONElement = ((JsonObject)restaurantsJSONArray.get(i)).get("restaurant");
  //get the restaurant name
  restaurantJSONPrimitive = ((JsonObject)restaurantJSONElement.getAsJsonObject()).getAsJsonPrimitive("name");
  restaurantName = restaurantJSONPrimitive.getAsString();
}

You could extract all the members and do whatever you want with them, put them in custom object arrays and sort them by restaurantName as the comparitor

3 Comments

Is Gson already included to android studios or do I have to import some library, because I'm getting a lot of "cannot resolve symbol" errors
nvm found out that you need to include the .jar file of gson in the libs folder then add it to the dependencies of the app heres a link for anyone wondering youtube.com/watch?v=jqv3Qkgop88&t=89s
Yes, I put a link in the answer that takes you to the GSON github and tells you... but on a second look it only explains the build.gradle inclusion. Hope this gets you started in the right direction

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.