Java Jackson @JsonPropertyOrder Example

1. Introduction

Jackson's @JsonPropertyOrder annotation allows you to specify the order in which fields are serialized into a JSON string. By default, the properties' order depends on their declaration in the class, but using this annotation, you can customize the order.

2. Example Steps

1. Create a Person class with several fields.

2. Annotate the class with @JsonPropertyOrder specifying the desired order of properties.

3. Serialize an instance of the Person class.

4. Observe the serialized JSON string's property order.

3. Java Jackson @JsonPropertyOrder Example

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonJsonPropertyOrderExample {

    public static void main(String[] args) throws Exception {
        // Initialize ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // Create an instance of Person
        Person person = new Person("John", "Doe", 30);

        // Serialize the Person instance to JSON string
        String serializedPerson = mapper.writeValueAsString(person);

        // Print the serialized string
        System.out.println(serializedPerson);
    }

    @JsonPropertyOrder({"age", "lastName", "firstName"})
    static class Person {
        private String firstName;
        private String lastName;
        private int age;

        public Person(String firstName, String lastName, int age) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
        }

        // Standard getters and setters
    }
}

Output:

{"age":30,"lastName":"Doe","firstName":"John"}

4. Step By Step Explanation

In the Person class, we used the @JsonPropertyOrder annotation to specify the order of properties in the serialized JSON. Even though the firstName field is declared before lastName in the class, in the serialized JSON, the lastName property appears before the firstName property due to our custom order. This demonstrates the effectiveness of the @JsonPropertyOrder annotation in determining the order of properties in the serialized output.


Comments