Home > Java > javaTutorial > body text

How can we sort JSONArray in Java?

WBOY
Release: 2023-09-14 16:21:03
forward
1444 people have browsed it

How can we sort JSONArray in Java?

JSON is one of the widely used data exchange formats and is a lightweightand>Languageindependent. JSONArray can parse the text in a string to generate a vector --like object, and supports the java.util.List interface.

We can sort a JSONArray in the example below.

Example

import java.util.*;
import org.json.*;
public class SortJSONArrayTest {
   public static void main(String[] args) {
      String jsonStr = "[ { \"ID\": \"115\", \"Name\": \"Raja\" },{ \"ID\": \"120\", \"Name\": \"Jai\" },{ \"ID\": \"125\", \"Name\": \"Adithya\" }]";
      JSONArray jsonArray = new JSONArray(jsonStr);
      JSONArray sortedJsonArray = new JSONArray();
      List list = new ArrayList();
      for(int i = 0; i < jsonArray.length(); i++) {
         list.add(jsonArray.getJSONObject(i));
      }
      System.out.println("Before Sorted JSONArray: " + jsonArray);
      Collections.sort(list, new Comparator() {
         private static final String KEY_NAME = "Name";
         @Override
         public int compare(JSONObject a, JSONObject b) {
            String str1 = new String();
            String str2 = new String();
            try {
               str1 = (String)a.get(KEY_NAME);
               str2 = (String)b.get(KEY_NAME);
            } catch(JSONException e) {
               e.printStackTrace();
            }
            return str1.compareTo(str2);
         }
      });
      for(int i = 0; i < jsonArray.length(); i++) {
        <strong> </strong>sortedJsonArray.put(list.get(i));
      }
      System.out.println("Sorted JSON Array with Name: " + sortedJsonArray);
   }
}
Copy after login

Output

Before Sorted JSONArray:
[{"ID":"115","Name":"Raja"},
   {"ID":"120","Name":"Jai"},
   {"ID":"125","Name":"Adithya"}]
Sorted JSON Array with Name:
[{"ID":"125","Name":"Adithya"},
   {"ID":"120","Name":"Jai"},
   {"ID":"115","Name":"Raja"}]
Copy after login

The above is the detailed content of How can we sort JSONArray in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template