【问题标题】:Sorting a JSON object in Android studios (java)在 Android 工作室 (java) 中对 JSON 对象进行排序
【发布时间】:2018-05-23 07:07:31
【问题描述】:

我一直在寻找如何对这样的 JSON 对象进行排序。它有很多属性,但我只是想按“名称”的字母顺序对对象进行排序:

我真的是 java 新手,所以你有任何可以开始的信息,那会很棒!

//更新:

所以我想出了如何提取每家餐厅的属性,现在我正在尝试实现一个比较器来对 json 对象进行排序,但我对如何调用比较器以及输入什么参数感到困惑

这是我正在使用的比较器(从互联网上获取的)

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);
        }
    }

我对如何对对象进行排序也有点困惑,因为它只会返回一个整数。我试图排序的 json 对象在下面

这是我连接到 zomato API 时收到的 JSON 对象

``

{
  "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": []
      }
    },

【问题讨论】:

  • 感谢您的关注,我已将其从问题中删除
  • 像 HashMap 一样,JSON 没有键排序的概念。你不打算把这个 JSON 解析成一个 Object 吗?

标签: java android json sorting parsing


【解决方案1】:

编写一个Comparator,根据它们各自的name 属性对一对JSON 对象进行排序。然后使用它对 JSON 对象数组进行排序;例如使用Arrays.sort(objects, comparator)

这是一个(更一般的)示例:

您可以修改该代码以将 OffersOrder 类替换为您的 JSON 对象类型(或自定义类),然后实现比较器以比较对象并返回适当的值。

【讨论】:

  • 好吧,我搜索了一下,发现了这段代码
  • 您找到的代码不是真正的 Java 代码。如果你想了解Arrays.sortCollections.sort 是如何工作的,javadoc 会解释它。
  • OK 我试试修改,谢谢!
  • 所以我查看了该代码,想知道如何将餐厅的名称放入列表中以便对名称进行排序?
  • 你没有。您编写比较器,以便它查看两个 JSON 对象并根据它们的 name 属性值进行比较。
【解决方案2】:

我只熟悉使用有点旧的 Google 的 gson 库。如果有更好的 json 解析器可用,我相信有人可以加入。 您可以像这样使用它来提取信息:

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();
}

您可以提取所有成员并对它们做任何您想做的事情,将它们放入自定义对象数组中并按 restaurantName 作为比较器对它们进行排序

【讨论】:

  • Gson 是否已经包含在 android studios 中,还是我必须导入一些库,因为我收到很多“无法解析符号”错误
  • nvm 发现您需要在 libs 文件夹中包含 gson 的 .jar 文件,然后将其添加到应用程序的依赖项中,这里有一个链接供任何想知道的人使用 youtube.com/watch?v=jqv3Qkgop88&t=89s
  • 是的,我在答案中放置了一个链接,该链接将您带到 GSON github 并告诉您……但再看一遍,它只解释了 build.gradle 包含。希望这能让你朝着正确的方向开始
猜你喜欢
  • 1970-01-01
  • 2017-06-07
  • 2018-02-13
  • 1970-01-01
  • 2011-05-12
  • 2013-07-15
  • 2020-03-06
  • 1970-01-01
相关资源
最近更新 更多