您可以將JSONstring轉換爲一個TreeMap,並使用您實現的Comparator按值進行比較,然後將此TreeMap轉換回JSON。
瞭解如何在這裏創建一個價值比較: http://www.programcreek.com/2013/03/java-sort-map-by-value/
然後用ObjectMapper到JSON轉換成地圖的地圖回JSON:
String json = "{\"address\" : \"def\","
+ "\"name\" : \"ghi\","
+ "\"phone\" : \"jkl\","
+ "\"age\" : \"def\","
+ "\"SSN\" : \"abc\"}";
Map<String, String> jsonMap = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
jsonMap = (mapper.readValue(json, Map.class));
Comparator<String> comparator = new ValueComparator(jsonMap);
Map<String, String> treeMap = new TreeMap<String, String>(comparator);
treeMap.putAll(jsonMap);
String sortedJson = mapper.writeValueAsString(treeMap);
System.out.println(sortedJson);
結果: {「SSN 「:」 ABC」, 「地址」: 「高清」, 「名」: 「GHI」, 「手機」: 「JKL」}
比較:
public class ValueComparator implements Comparator<String> {
Map<String, String> map = new HashMap<String, String>();
public ValueComparator(Map<String, String> map){
this.map = map;
}
@Override
public int compare(String s1, String s2) {
return map.get(s1).compareTo(map.get(s2));
}
}
來源
2016-10-12 08:05:25
sas
您的意思是「使用屬性對此JSON字符串進行排序」。按地址按字母順序排列上述條目? – hammerfest