JSON elements are arranged in a random order by default. This shot covers how to use Jackson to display JSON elements in a particular order.
Jackson is a popular and powerful library in Java that is used to deal with JSON data.
Note: To use the Jackson library, add the Jackson databind dependency from the Maven Repository.
@JsonPropertyOrder
annotationWhen the Java object is converted to JSON, we can use the @JsonPropertyOrder
annotation to specify the order that the JSON elements should be in.
@JsonPropertyOrder({attr1, attr2, attr3})
The annotation takes in different attributes of the class. The attributes mentioned in the annotation are first serialized to JSON in the order defined, followed by other properties in the class.
In the code below, we define a Student
class that has firstName
, middleName
, lastName
, age
, and id
as attributes. We add @JsonPropertyOrder
to the Student
class, which takes in the different attributes of the class.
The output of the code is as follows:
{
"firstName":"firstName",
"middleName":"middleName",
"lastName":"lastName",
"id":123,
"age":20
}
First, we get the attributes in the annotation in the order they are defined, followed by other attributes of the class.
import com.fasterxml.jackson.annotation.JsonPropertyOrder;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;public class Main{@JsonPropertyOrder({"firstName", "middleName", "lastName"})static class Student{private int id;private int age;private String firstName;private String middleName;private String lastName;public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getMiddleName() {return middleName;}public void setMiddleName(String middleName) {this.middleName = middleName;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public int getId() {return id;}public void setId(int id) {this.id = id;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}public static void main(String[] args) throws JsonProcessingException {Student student = new Student();student.setFirstName("firstName");student.setMiddleName("middleName");student.setLastName("lastName");student.setId(123);student.setAge(20);ObjectMapper objectMapper = new ObjectMapper();String studentJson = objectMapper.writeValueAsString(student);System.out.println(studentJson);}}