gpt4 book ai didi

Java : Sort JSON String using key

转载 作者:行者123 更新时间:2023-12-01 09:23:56 36 4
gpt4 key购买 nike

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

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"
}
]

请解释一下。

最佳答案

您可以使用您实现的比较器将 JSONstring 转换为 TreeMap 以按值进行比较,然后将此 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","地址":"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));
}
}

关于Java : Sort JSON String using key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39992966/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com