1

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

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.

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

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
  • 1
    The easiest way would be to sort your List or array before you serialize it. – Jo Peyper Feb 22 '17 at 05:32
  • Thanks for the reply Jo. But I don't want to sort the list. Can't it be done by Jackson anyway. – Abhishek Kumar Maurya Feb 22 '17 at 05:45
  • I guess you could use a [customer serializer](http://wiki.fasterxml.com/JacksonHowToCustomSerializers) to copy and sort the list during serialization. The trick will be trying to get access to your users preferences inside the serializer. – Jo Peyper Feb 22 '17 at 05:49

1 Answers1

2

Option 1 :

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.

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

Option 2 :

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);

Option 3 :

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

ravthiru
  • 8,878
  • 2
  • 43
  • 52