我已经寻找了一段时间,想要一种对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, "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", } ]}
并按字母顺序按值“ COMMERCIALNAME_E”得到:
{"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" } ]}
我找不到任何可以做到这一点的代码。谁能给我些帮助?
将这些JSON解析为“对象集合”,然后使用比较器通过您喜欢的字段对其进行排序。
例:
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);