• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Java使用键对JSON字符串排序

用户头像
it1352
帮助1

问题说明

我有一个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"
  }
]

请解释。

正确答案

#1

您可以使用实现的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
系列文章
更多 icon
同类精品
更多 icon
继续加载