How to sort JSON object in java?

后端 未结 5 855
一个人的身影
一个人的身影 2020-12-06 01:35

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

{\"results\": [
  {
    \"layerId\": 5,
    \"layerName\": \"Pharmaceutical En         


        
相关标签:
5条回答
  • 2020-12-06 02:04

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

    • Use GSON to parse it to collection of objects

    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.

    Person p = new Person();
    p.setName("Jigar");
    p.setAge(22);
    String jsonStr = new com.google.gson.Gson().toJson(obj);
    
    0 讨论(0)
  • 2020-12-06 02:12

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

    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);
    }
    
    }
    
    0 讨论(0)
  • 2020-12-06 02:15

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

    0 讨论(0)
  • 2020-12-06 02:17

    Boon provides JSON sorting, searching, filtering and more.

    Check out:

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

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

    0 讨论(0)
  • 2020-12-06 02:21

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

     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()));
    }
    
    0 讨论(0)
提交回复
热议问题