Java:使用key对JSON字符串进行排序

时间:2016-10-12 07:34:28

标签: java json csv

我有一个JSON格式的String。我需要使用属性对此JSON字符串进行排序,但无法执行此操作。通过读取CSV文件创建JSON字符串。我不想再次读取CSV并且必须仅使用JSON String来实现它。有没有办法做到这一点?请告诉我。

JSON字符串格式为:

[
  {
    "address": "some address",
    "name": "some name",
    "phone": "some phone",
    "age": "some age",
    "SSN": "some SSN"
  },
  {
    "address": "abc",
    "name": "def",
    "phone": "ghi",
    "age": "jkl",
    "SSN": "mno"
  }
]

请解释。

1 个答案:

答案 0 :(得分:1)

您可以使用您实现的比较器将JSONstring转换为TreeMap,以便按值进行比较,然后将此TreeMap转换回JSON。

在此处查看如何创建值Comparator: 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”, “地址”: “DEF”, “名称”: “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));
   }
 }