如何在java中对JSON对象进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4277715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:16:38  来源:igfitidea点击:

How to sort JSON object in java?

javajson

提问by Venkatesh Goud

I've been looking for a while and want a way to sort a JSON object like this:

我一直在寻找一段时间,想要一种对 JSON 对象进行排序的方法,如下所示:

{"results": [
  {
    "layerId": 5,
    "layerName": "Pharmaceutical Entities",
    "attributes": {
      "OBJECTID": "35",
      "FACILITYTYPE": "Pharmacy",
      "FACILITYSUBTYPE": "24 Hr Pharmacy",
      "COMMERCIALNAME_E": "SADD MAARAB PHARMACY"
      },
    "geometryType": "esriGeometryPoint",
   },
  {
    "layerId": 5,
    "layerName": "Pharmaceutical Entities",
    "attributes": {
      "OBJECTID": "1",
      "FACILITYTYPE": "Pharmacy",
      "FACILITYSUBTYPE": "24 Hr Pharmacy",
      "COMMERCIALNAME_E": "GAYATHY HOSPITAL  PHARMACY"
    },
    "geometryType": "esriGeometryPoint",
  },
     {
    "layerId": 5,
    "layerName": "Pharmaceutical Entities",
    "attributes": {
      "OBJECTID": "255",
      "FACILITYTYPE": "Pharmacy",
      "FACILITYSUBTYPE": "24 Hr Pharmacy",
      "COMMERCIALNAME_E": "AL DEWAN PHARMACY"
      },
    "geometryType": "esriGeometryPoint",
   }
]}

and sort is alphabetically by value of "COMMERCIALNAME_E" to get:

并按字母顺序按“COMMERCIALNAME_E”的值排序以获得:

{"results": [
   {
    "layerId": 5,
    "layerName": "Pharmaceutical Entities",
    "attributes": {
      "OBJECTID": "255",
      "FACILITYTYPE": "Pharmacy",
      "FACILITYSUBTYPE": "24 Hr Pharmacy",
      "COMMERCIALNAME_E": "AL DEWAN PHARMACY"
      },
    "geometryType": "esriGeometryPoint"
   },
  {
    "layerId": 5,
    "layerName": "Pharmaceutical Entities",
    "attributes": {
      "OBJECTID": "1",
      "FACILITYTYPE": "Pharmacy",
      "FACILITYSUBTYPE": "24 Hr Pharmacy",
      "COMMERCIALNAME_E": "GAYATHY HOSPITAL  PHARMACY"
       },
    "geometryType": "esriGeometryPoint"
   },
   {
    "layerId": 5,
    "layerName": "Pharmaceutical Entities",
    "attributes": {
      "OBJECTID": "35",
      "FACILITYTYPE": "Pharmacy",
      "FACILITYSUBTYPE": "24 Hr Pharmacy",
      "COMMERCIALNAME_E": "SADD MAARAB PHARMACY"
      },
    "geometryType": "esriGeometryPoint"
   }
]}

I can't find any code that will do this. Can anyone give me some help?

我找不到任何可以执行此操作的代码。任何人都可以给我一些帮助吗?

采纳答案by Jigar Joshi

Parse these JSON to Collection of Objects and use comparator to sort it using your preferred field.

将这些 JSON 解析为对象集合,并使用比较器使用您的首选字段对其进行排序。

Example:

例子:

import com.google.gson.Gson;

class Person {
  private int age;
  private String name;
}

String json = "{'age':22,'name':'Jigar'}";
Gson gson = new Gson();
TestJsonFromObject obj = gson.fromJson(json, Person.class);  

If you want to create JSON from Object.

如果你想从 Object 创建 JSON。

Person p = new Person();
p.setName("Jigar");
p.setAge(22);
String jsonStr = new com.google.gson.Gson().toJson(obj);

回答by Bart van Heukelom

You can write a List<JSONObject>wrapper around the JSON array, then use Collections.sortwith a custom Comparator<JSONObject>.

您可以List<JSONObject>围绕 JSON 数组编写包装器,然后Collections.sort与自定义Comparator<JSONObject>.

回答by RickHigh

Boon provides JSON sorting, searching, filtering and more.

Boon 提供 JSON 排序、搜索、过滤等功能。

Check out:

查看:

http://www.dzone.com/links/r/sorting_for_java_instances_maps_java_collections.html(Boon Sorting)

http://www.dzone.com/links/r/sorting_for_java_instances_maps_java_collections.html(恩惠排序)

    Object jsonObject = fromJson(json);
    List<?> jsonDepartments = (List<?>) jsonObject;
    List<?> jsonEmployees = (List<Employee>) atIndex(jsonDepartments, "employees");

    sort(employees); //natural sort


    sort( employees, "lastName"); //sort by last name



    sort( departmentList ); //natural sort



    sort( employees, sortBy( "department.name" ),
                     sortByDescending( "lastName" ),
                     sortBy( "firstName" ) ); //you get the idea



    sort(employees,
            sortBy("contactInfo.phoneNumbers[0]")); //you can even sort by a path expression




    sort( employees,
            sortByDescending("contactInfo.phoneNumbers[0]") ); //backwards by a path expression


    max(employees); //gets the max (natural order employee)


    greatest(employees, 5); //gets the top five


    min(employees); //gets the lowest



    least(employees, 5); //gets the lowest five


    max(employees, "salary"); //gets the top salaried employee

    greatest(employees, "salary", 5); //gets the top five salaried employees


    min(employees, "salary"); //the least

    least(employees, "salary", 5); //the lowest five salaried employees

Boon is also currently the fastest JSON parser on the JVM (circa March 2014).

Boon 也是目前 JVM 上最快的 JSON 解析器(大约 2014 年 3 月)。

回答by Sarneet Kaur

I used JSON simple API to sort this. Here is my code:

我使用 JSON 简单 API 对此进行排序。这是我的代码:

import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class SortJSON {

public static void main(String[] args) {
    JSONParser parser = new JSONParser();
    try {
        JSONObject o = (JSONObject) parser.parse(new FileReader("test3.json"));
        JSONArray array = (JSONArray) o.get("results");
        ArrayList<JSONObject> list = new ArrayList<>();

        for (int i = 0; i < array.size(); i++) {
            list.add((JSONObject) array.get(i));
        }
        Collections.sort(list, new MyJSONComparator());

        for (JSONObject obj : list) {
            System.out.println(((JSONObject) obj.get("attributes")).get("OBJECTID"));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

class MyJSONComparator implements Comparator<JSONObject> {

@Override
public int compare(JSONObject o1, JSONObject o2) {
    String v1 = (String) ((JSONObject) o1.get("attributes")).get("COMMERCIALNAME_E");
    String v3 = (String) ((JSONObject) o2.get("attributes")).get("COMMERCIALNAME_E");
    return v1.compareTo(v3);
}

}

回答by Malkeith Singh

I used Hymansonto do it. Below is sort method implementation you can probably add more checks to it and add a return type

我用Hyman逊来做这件事。下面是 sort 方法的实现,您可以向它添加更多检查并添加返回类型

 public void sort(String data) throws IOException {
    JsonNode node = new ObjectMapper().readTree(data);
    ArrayNode array = (ArrayNode) node.get("results");
    Iterator<JsonNode> i =array.elements();
    List<JsonNode> list = new ArrayList<>();
    while(i.hasNext()){
        list.add(i.next());
    }
    list.sort(Comparator.comparing(o -> o.get("attributes").get("COMMERCIALNAME_E").asText()));
}