Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort JSON object in java?

Tags:

java

json

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

{"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:

{"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?

like image 201
Venkatesh Goud Avatar asked Nov 25 '10 13:11

Venkatesh Goud


People also ask

Can you sort a JSON object?

JSON return type is an array of objects. Hence sort method cannot be used directly to sort the array. However, we can use a comparer function as the argument of the 'sort' method to get the sorting implemented.

How do I sort items in JSON?

Example-1: Sort JSON object using json.The value of the sort_keys argument of the dumps() function will require to set True to generate the sorted JSON objects from the array of JSON objects. Create a python file with the following script sort the JSON objects using json. dumps() function.

Can we sort JSON array in Java?

A JSONArray can parse text from a String to produce a vector-like object and supports java. util. List interface. We can sort a JSONArray in the below example.

Is Order important in JSON?

The JSON RFC (RFC 4627) says that order of object members does not matter.

How to sort the values of a jsonobject in Java?

The constructor of a JSONObject can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get () and opt () methods or to convert values into a JSON text using the put () and toString () methods. In the below example, we can sort the values of a JSONObject in the descending order.

How to sort JSON array by key in Python?

Following sortByKey () function takes JSON Object as an input and returns JSON Array which is sorted by key. We will create JSON Array of [jsonValue, jsonKey] from JSON Object.

How to sort data in Java?

Sorting in Java 1 Arrays.Sort () works for arrays which can be of primitive data type also.#N#import java.util.Arrays;#N#public class GFG... 2 Collections.sort () works for objects Collections like ArrayList and LinkedList.#N#import java.util. 3 ;#N#public class GFG... More ...

Where is the sorted jsonarray stored in Java?

The sorted JSONArray is now stored in the sortedJsonArray object. Not the answer you're looking for? Browse other questions tagged java json sorting or ask your own question.


1 Answers

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

}
like image 196
Sarneet Kaur Avatar answered Oct 13 '22 17:10

Sarneet Kaur