通过Jackson生成的Json应该按Json元素值的排序顺序 [英] Json generated through Jackson should be in sorted order of the Json elements value

查看:183
本文介绍了通过Jackson生成的Json应该按Json元素值的排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照JSON元素值的排序顺序从Map生成JSON字符串.这是我的JSON

I am trying to generate JSON string from Map in sorted order of json element's value. Here is my JSON

"customer": {
      "id": "168252733",
      "firstName": "OTP",
      "lastName": "KPI",
      "contact": {
        "emailAddress": "nona.adams1@gmail.com",
        "phone": [
          {
            "number": "2567775065",
            "type": "primary"
          },
          {
            "number": "2567775065",
            "type": "secondary"
          }
        ]
      }
    }

这个Json可以包含多个客户记录,但是我希望生成的json应该根据用户的喜好按照姓,名或电子邮件的排序顺序进行.

This Json can contains multiple customer records but I want the json to be generated should be in sorted order of either firstname, lastname or email depending on the user preference.

我是JACKSON的新手,不知道如何实现它.有人可以帮我吗?预先感谢.

I am new to JACKSON, don't know how to implement it. Can anybody help me on this. Thanks in Advance.

推荐答案

选项1:

简单的方法是在序列化之前使用 Arrays.sort(T [] a,Comparator )对用户列表进行排序.

Simple way will be to use Arrays.sort(T[] a, Comparator<? super T> c) to sort the List of Customers based on user preference before serialize.

您需要为每个用户首​​选项创建比较器,然后使用 Arrays.sort(customerList,firstNameComparator)

You need to create Comparators for each user preference and then use Arrays.sort(customerList, firstNameComparator)

选项2:

如果要从JSON排序客户列表,则需要注册Custom Deserializer,然后您的 CustomerListDeserializer 生成客户排序列表

If you want sorted List of Customers from JSON then you need to register Custom Deserializer and your CustomerListDeserializer generate sorted list of Customers

  SimpleModule simpleModule = new SimpleModule().addDeserializer(CustomerList.class, new CustomerListDeserializer());
        mapper.registerModule(smipleModule);

选项3:

首先反序列化为客户对象列表",然后应用排序.

First Deserialize into to List of Customer Objects and then apply sort.

这篇关于通过Jackson生成的Json应该按Json元素值的排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆