如何在java中对JSON对象进行排序?

前端之家收集整理的这篇文章主要介绍了如何在java中对JSON对象进行排序?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在寻找一段时间,想要一种方法来排序这样的 JSON对象:
{"results": [
  {
    "layerId": 5,"layerName": "Pharmaceutical Entities","attributes": {
      "OBJECTID": "35","FACILITYTYPE": "Pharmacy","FACILITYSUBTYPE": "24 Hr Pharmacy","COMMERCIALNAME_E": "SADD MAARAB PHARMACY"
      },"geometryType": "esriGeometryPoint",},{
    "layerId": 5,"attributes": {
      "OBJECTID": "1","COMMERCIALNAME_E": "GAYATHY HOSPITAL  PHARMACY"
    },"attributes": {
      "OBJECTID": "255","COMMERCIALNAME_E": "AL DEWAN PHARMACY"
      },}
]}

并按“COMMERCIALNAME_E”的值按字母顺序排序:

{"results": [
   {
    "layerId": 5,"geometryType": "esriGeometryPoint"
   },"COMMERCIALNAME_E": "GAYATHY HOSPITAL  PHARMACY"
       },"geometryType": "esriGeometryPoint"
   }
]}

我找不到任何可以执行此操作的代码.谁能给我一些帮助?

解决方法

将这些JSON解析为对象集合,并使用比较器使用首选字段对其进行排序.

> Use GSON to parse it to collection of objects

例:

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

如果要从Object创建JSON.

Person p = new Person();
p.setName("Jigar");
p.setAge(22);
String jsonStr = new com.google.gson.Gson().toJson(obj);
原文链接:https://www.f2er.com/java/127891.html

猜你在找的Java相关文章