How to serialize the order of properties using the Jackson library in Java?



In this article, let's learn about the serialization of the order of properties using the Jackson library in Java. The Jackson library is used for processing JSON data in Java.

The @JsonPropertyOrder is an annotation to be used at the class level. It takes as property a list of fields that defines the order in which fields can appear in the string resulting from the object JSON serialization. The properties included in the annotation declaration can be serialized first(in defined order), followed by any properties not included in the definition.

Steps to serialize the order of properties using the Jackson library in Java:

  • In order to use Jackson, you will need to add it to your project. If you use Maven, add the following dependency to your pom.xml file:
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.15.2</version>
</dependency>

Or, if you are not using Maven, you can download the Jackson library from here.

  • Define your POJO class with the @JsonPropertyOrder annotation.
  • Use the ObjectMapper class to serialize the object to JSON.
  • Example

    In the below example, we will create a class Person with fields for name and age. We will then serialize this POJO into JSON using Jackson's ObjectMapper class.

    Following is the code to serialize the order of properties using the Jackson library in Java:

    import com.fasterxml.jackson.annotation.JsonPropertyOrder;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.io.IOException;
    
    @JsonPropertyOrder({ "name", "age" })
    public class Person {
       private String name;
       private int age;
    
       public Person(String name, int age) {
          this.name = name;
          this.age = age;
       }
    
       public String getName() {
          return name;
       }
    
       public int getAge() {
          return age;
       }
    
       public static void main(String[] args) throws IOException {
          Person person = new Person("Ansh", 23);
          ObjectMapper objectMapper = new ObjectMapper();
          String jsonString = objectMapper.writeValueAsString(person);
          System.out.println(jsonString);
       }
    }
    

    Output

    Following is the output of the above code:

    {"name":"Ansh","age":23}
    
    Aishwarya Naglot
    Aishwarya Naglot

    Writing clean code… when the bugs aren’t looking.

    Updated on: 2025-09-01T13:33:44+05:30

    4K+ Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements