【问题标题】:How to sort JSON object in java?如何在java中对JSON对象进行排序?
【发布时间】:2010-11-25 13:45:56
【问题描述】:

我一直在寻找一段时间,想要一种像这样对 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",
   }
]}

并按“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"
   }
]}

我找不到任何可以执行此操作的代码。谁能帮帮我?

【问题讨论】:

    标签: java json


    【解决方案1】:

    我使用 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);
    }
    
    }
    

    【讨论】:

    • 这绝对是一个很好的答案。但我仍然会将 json 元素转换为 Java 对象(PO​​JO)并使用比较器进行过滤/排序。我可以看到这种方法用于非面向生产的自动化测试,但对于面向生产的代码,我会付出更多努力并进行适当的域映射。
    【解决方案2】:

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

    例子:

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

    如果你想从 Object 创建 JSON。

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

    【讨论】:

    • 谢谢,但是我动态地得到这个对象(当我调用 Web 服务时)是否可以使用 tostring() 方法或任何其他方法将 json 对象转换为字符串,请帮助我
    • @venkatesh 如果您要求从 Object 创建 JSON,而不是使用 new com.google.gson.Gson().toJson(obj);
    • 谢谢, JSONObject obj= /** json 对象数据 **/ 然后 String str = obj.toString();这是正确的吗 ?请解释清楚
    • 谢谢,我的最后一个问题是例如 object1 是我的 jsonobject 我可以将这个 json 对象直接转换为字符串类型意味着 String jsonstr= object1;但是您选择了一个数据属于 json 对象的类在我的项目中,我动态地获取这些数据意味着数据可能每天都在变化。不可能每次都编写这种类型的类。对不起我的英语
    【解决方案3】:

    我使用 Jackson 来做到这一点。下面是 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()));
    }
    

    【讨论】:

    • 我很难做到这一点,而您的回答是时间的救星。谢谢
    【解决方案4】:

    您可以在 JSON 数组周围编写 List&lt;JSONObject&gt; 包装器,然后将 Collections.sort 与自定义 Comparator&lt;JSONObject&gt; 一起使用。

    【讨论】:

      【解决方案5】:

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

      退房:

      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 也是目前 JVM 上最快的 JSON 解析器(大约 2014 年 3 月)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-08
        • 2018-10-31
        • 2017-06-07
        • 2018-02-13
        • 2015-05-11
        • 2018-05-23
        • 2011-05-12
        相关资源
        最近更新 更多