Java:使用键对JSON字符串排序 [英] Java : Sort JSON String using key
问题描述
我有一个JSON格式的字符串。我需要使用属性对这个JSON字符串进行排序,但是无法做到这一点。 JSON字符串是通过读取CSV文件创建的。我不想再次读取CSV,而只能使用JSON String来实现它。有没有办法做到这一点?请让我知道。
I have a String which is in JSON format. I need to sort this JSON string using attributes but am unable to do it. JSON String is created by reading a CSV file. I do not want to read the CSV again and have to implement it using JSON String only. Is there a way to do that? Please let me know.
JSON字符串格式为:
JSON String format is :
[
{
"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"
}
]
请解释。
推荐答案
您可以使用实现的Comparator将JSONstring转换为TreeMap,以按值进行比较,然后将此TreeMap转换回JSON。
You can convert the JSONstring into a TreeMap with a Comparator you implement to compare by value, and then convert this TreeMap back to JSON.
在此处创建值比较器:
http:/ /www.programcreek.com/2013/03/java-sort-map-by-value/
See how to create a value Comparator here: http://www.programcreek.com/2013/03/java-sort-map-by-value/
然后使用ObjectMapper将JSON转换为将地图映射回JSON:
And then use ObjectMapper to convert the JSON into a map the the map back to 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, address: def , name: ghi, phone: jkl}
Result: {"SSN":"abc","address":"def","name":"ghi","phone":"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));
}
}
这篇关于Java:使用键对JSON字符串排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!