17

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?

6 Answers 6

13

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

}
1
  • This is definitely a good answer. But I would still convert json element to Java object (POJO) and do filtering/sorting using Comparators. I can see this approach for say non-production facing automation tests but for a production facing code I would put in more effort and do proper domain mapping.
    – nabster
    Commented Sep 4, 2019 at 16:26
6

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

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);
4
  • 1
    Thanks, But I get this object at dynamically(when i called web service) Is it possibile to convert json object to string using tostring() method or any onther method require please help me Commented Nov 25, 2010 at 14:03
  • @venkatesh if you are asking to create JSON from Object than its very well possible using new com.google.gson.Gson().toJson(obj); Commented Nov 25, 2010 at 14:08
  • Thanks, JSONObject obj= /** json object data **/ then String str = obj.toString(); is it correct ? please explain clearly Commented Nov 25, 2010 at 15:19
  • Thank you, My last Question is for example object1 is my jsonobject can i convert this json object directly to string type means String jsonstr= object1; but you have taken a class which have the data belongs to json object In my project i am getting this data dynamically means data may change day by day.it is not possible to write this type of class every time. sorry for my english Commented Nov 25, 2010 at 15:51
5

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()));
}
1
  • I was having a tough time to do this and your answer is a saviour of time. Thanks Commented Apr 16, 2020 at 11:51
2

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

0
2

Boon provides JSON sorting, searching, filtering and more.

Check out:

https://web.archive.org/web/20231123101220/https://rick-hightower.blogspot.com/2014/03/boon-sorting-for-java-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

This is the way what I sorted from gson.

Param: 1. jsonArray, 2. member Name to be sorted

sample JSON:

[{
    "name": "foo",
    "value": "sam"
},
{
    "name": "doo",
    "value": "cool"
},
{
    "name": "app",
    "value": "Zip"
},
{
    "name": "mol",
    "value": "JOUL"
},
{
    "name": "number",
    "value": "123"
}]

code :

private static JsonArray JsonObjectSort(final JsonArray jsonArray, final String sortBy) {
    final JsonArray sortedArr = new JsonArray();
    final ArrayList<JsonObject> listJsonObj = new ArrayList<>();
    for (int i = 0; i < jsonArray.size(); i++) {
        listJsonObj.add((JsonObject) jsonArray.get(i));
    }

    Collections.sort(listJsonObj,
            (o1, o2) -> o1.get(sortBy).getAsString().compareToIgnoreCase(o2.get(sortBy).getAsString()));

    for (int i = 0; i < jsonArray.size(); i++) {
        sortedArr.add(listJsonObj.get(i));
    }
    System.out.println(sortedArr);
    return sortedArr;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.