Java使用键对JSON字符串排序
问题说明
我有一个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));
}
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfggeg
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20