Dependencies
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
- jackson-annotations-2.9.8.jar
- jackson-core-2.9.8.jar
- jackson-databind-2.9.8.jar
Jackson @JsonPropertyOrder Example
User.java
package net.javaguides.jackson.annotations;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder({
"fullName",
"id",
"firstName",
"lastName"
})
public class User {
public int id;
private String firstName;
private String lastName;
private String fullName;
public User(int id, String firstName, String lastName, String fullName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.fullName = fullName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
JacksonPropertyOrderDemo.java
package net.javaguides.jackson.annotations;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JacksonPropertyOrderDemo{
public static void main(String[] args) throws IOException {
// Create ObjectMapper object.
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
User bean = new User(1, "Ramesh", "Fadatare", "Ramesh Fadatare");
String result = mapper.writeValueAsString(bean);
System.out.println(result);
}
}
{
"fullName" : "Ramesh Fadatare",
"id" : 1,
"firstName" : "Ramesh",
"lastName" : "Fadatare"
}
Order the Properties Alphabetically
@JsonPropertyOrder(alphabetic=true)
public class User {
private int id;
private String firstName;
private String lastName;
private String fullName;
{
"firstName" : "Ramesh",
"fullName" : "Ramesh Fadatare",
"id" : 1,
"lastName" : "Fadatare"
}
Related Articles
- Change Field Name in JSON using Jackson (popular)
GitHub Repository
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment