How to sort GSON Array based on a key?

后端 未结 3 710
遇见更好的自我
遇见更好的自我 2020-12-10 07:29

Consider the following is my Array

[
  {\"id\":10,\"name\":\"name10\",\"valid\":true},
  {\"id\":12,\"name\":\"name12\",\"valid\":false},
  {\"id\":11,\"name         


        
相关标签:
3条回答
  • 2020-12-10 07:48

    Try this library method as a simple JSON-level alternative to model classes creation:

    /**
     * Sort JSON-array by a given key name (numbers or text expected).
     *
     * @param jsonArray     JSON-array to sort.
     * @param keyNameToSort Key name to sort by. Expected are integer type 
     *                      (sorted ascending) or string type (sorted 
     *                      alphabetically).
     */
    public static JsonArray
    sortJsonArrayByKey(
      JsonArray jsonArray,
      String keyNameToSort) {
    
      JsonArray sortedJsonArray = new JsonArray();
      JsonObject jsonObject = null;
      int jsonElementIndex;
      TreeMap<Integer, JsonObject> integerSortedObjects = new TreeMap<>();
      TreeMap<String, JsonObject> stringSortedObjects = new TreeMap<>();
    
      for (
        jsonElementIndex = 0;
        jsonElementIndex < jsonArray.size();
        jsonElementIndex++) {
    
        try {
    
          // A JSON-Object from JSON-array:
    
          jsonObject =
            jsonArray
              .get(
                jsonElementIndex)
              .getAsJsonObject();
    
        } catch (Exception notAnObject) {
        }
    
        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
    
          // Look for the given key in the JSON-object:
    
          if (
            entry.getKey()
            .equals(keyNameToSort)) {
    
            try {
    
              // If key is of integer type:
    
              integerSortedObjects.put(
                entry
                  .getValue()
                  .getAsInt(),
                jsonObject);
    
            } catch (Exception notAnInt) {
    
              try {
    
                // If key is of string type:
    
                stringSortedObjects.put(
                  entry
                    .getValue()
                    .getAsString(),
                  jsonObject);
    
              } catch (Exception neitherIntNorString) {
              }
            }
          }
        }
      }
    
      // Add sorted by number values first:
    
      for (Integer key : integerSortedObjects.keySet()) {
    
        sortedJsonArray.add(
          integerSortedObjects.get(
            key));
      }
    
      // Add sorted by string values second:
    
      for (String key : stringSortedObjects.keySet()) {
    
        sortedJsonArray.add(
          stringSortedObjects.get(
            key));
      }
    
      return sortedJsonArray;
    }
    
    0 讨论(0)
  • 2020-12-10 08:05

    First of all, the proper way to parse your JSON is to create a class to encapsulate your data, such as:

    public class MyClass {
        private Integer id;
        private String name;
        private Boolean valid;
        //getters & setters
    }
    

    And then:

    Type listType = new TypeToken<List<MyClass>>() {}.getType();
    List<MyClass> myList = new Gson().fromJson(strArrayText, listType);
    

    Now you have a List and you want to sort it by the value of the attribute id, so you can use Collections as explained here:

    public class MyComparator implements Comparator<MyClass> {
        @Override
        public int compare(MyClass o1, MyClass o2) {
            return o1.getId().compareTo(o2.getId());
        }
    }
    

    And finally:

    Collections.sort(myList, new MyComparator());
    
    0 讨论(0)
  • 2020-12-10 08:07

    you can use Gson library https://sites.google.com/site/gson/gson-user-guide to get the Array(the class should implement comparable) and sort with arrays.sort();

    Thanks

    0 讨论(0)
提交回复
热议问题