2010-11-25 5 views
4

J'ai cherché pendant un certain temps et que vous voulez un moyen de trier un objet JSON comme ceci:Comment trier un objet JSON dans Java?

{"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", 
    } 
]} 

et est par trier par ordre alphabétique valeur de « COMMERCIALNAME_E » pour obtenir:

{"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 ne trouve aucun code qui le fera. Est-ce que quelqu'un peut m'aider?

Répondre

5

Parcourez ces JSON pour COllection d'objets et utilisez comparateur pour le trier en utilisant votre champ préféré.

Exemple:

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

Si vous voulez créer JSON de l'objet.

Person p = new Person(); 
p.setName("Jigar"); 
p.setAge(22); 
String jsonStr = new com.google.gson.Gson().toJson(obj); 
+0

Merci, mais je reçois cet objet à dynamiquement (quand j'ai appelé le service Web) Est-il possibile pour convertir la méthode ou toute autre méthode onther objet JSON à chaîne à l'aide toString() nécessitent s'il vous plaît aidez-moi –

+0

@venkatesh si vous demandez à créer JSON à partir de l'objet que son très bien possible en utilisant 'new com.google.gson.Gson(). toJson (obj);' –

+0

Merci, JSONObject obj =/** données d'objet json **/then String str = obj.toString(); est-ce correct ? veuillez expliquer clairement –

2

Vous pouvez écrire un wrapper List<JSONObject> autour du tableau JSON, puis utilisez Collections.sort avec une coutume Comparator<JSONObject>.

+1

comment faire cela? – RicardoE

3

Boon fournit le tri JSON, la recherche, le filtrage et plus encore.

Départ:

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

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 est aussi actuellement l'analyseur de JSON le plus rapide sur la machine virtuelle Java (vers Mars 2014).

3

J'ai utilisé l'API JSON simple pour trier ceci. Voici mon 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

Cela nécessite plus de votes. –