Total Pageviews

2018/06/12

[jackson] How to define ordering when serializing object properties to JSON ?

Problem
How to define ordering when serializing object properties to JSON ?
Employ class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
  package test.albert.jackson;
  
  import lombok.Builder;
  import lombok.Data;
  
  @Data
  @Builder
  public class Employee {
  
      private Integer id;
  
      private String name;
  
      private String email;
  
      private String phone;
  
      private Address address;
  
  }


Address class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
  package test.albert.jackson;
  
  import lombok.Builder;
  import lombok.Data;
  
  @Data
  @Builder
  public class Address {
  
      private String streetAddress;
      private String city;
      private String zipCode;
  
  }


Using ObjectMapper to serialize object properties to JSON
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  package test.albert.jackson;
  
  import java.io.IOException;
  
  import com.fasterxml.jackson.databind.ObjectMapper;
  
  import lombok.extern.slf4j.Slf4j;
  
  @Slf4j
  public class JacksonTest {
  
      public static void main(String[] args) throws IOException {
          Address address = Address.builder().zipCode("110").city("台北市").streetAddress("信義區信義路五段7號").build();
          Employee albert = Employee.builder().id(1).name("Albert").email("albert@gmail.com").phone("0900123456")
                  .address(address).build();
          
          ObjectMapper mapper = new ObjectMapper();
          
          // convert object to JSON
          String json = mapper.writeValueAsString(albert);
          log.debug(json);
      }
  
  }


How-to
You can make good use of @JsonPropertyOrder to define the ordering, for example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  package test.albert.jackson;
  
  import com.fasterxml.jackson.annotation.JsonPropertyOrder;
  
  import lombok.Builder;
  import lombok.Data;
  
  @Data
  @Builder
  @JsonPropertyOrder({ "id", "name", "address", "phone", "email" })
  public class Employee {
  
      private Integer id;
  
      private String name;
  
      private String email;
  
      private String phone;
  
      private Address address;
  
  }


No comments: