JSON Fields Order using Jackson @JsonPropertyOrder Examples
- Details
- Written by Nam Ha Minh
- Last Updated on 20 September 2023   |   Print Email
public class LocationDTO { private String code; @JsonProperty("city_name") private String cityName; @JsonProperty("region_name") private String regionName; @JsonProperty("country_name") private String countryName; @JsonProperty("country_code") private String countryCode; private boolean enabled; // getters and setters... }You can see the fields in this class is declared in this order: code, city_name, region_name, country_name, country_code and enabled. But the API GET /v1/locations/{code} may return a JSON object as follows:
{ "code": "MBMHR_IN", "enabled": true, "city_name": "Mumbai", "region_name": "Maharashtra", "country_name": "India", "country_code": "IN" }So how to sort the fields in this JSON object in a specific order? With FasterXML/Jackson library, you can use the @JsonPropertyOrder. For example:
@JsonPropertyOrder( {"code", "city_name", "region_name", "country_code", "country_name", "enabled"} ) public class LocationDTO { // fields... }You pass an array of String specifies the field names in the order declared in the array. Then the output will be as expected:
{ "code": "MBMHR_IN", "city_name": "Mumbai", "region_name": "Maharashtra", "country_code": "IN", "country_name": "India", "enabled": true }Note that using the @JsonPropertyOrder annotation, you don’t have to specify all the field names. That means you can just specify order of some fields that should be appeared first, and the order of the remaining fields is not set. For example:
@JsonPropertyOrder({"code", "city_name"}) public class LocationDTO { // fields.... }This ensures that the field code will come first, then followed by city_name. And the remaining fields can be in unspecified order. The output maybe as below:
{ "code": "MBMHR_IN", "city_name": "Mumbai", "enabled": true, "region_name": "Maharashtra", "country_name": "India", "country_code": "IN" }If you want to specify the fields sorted by alphabetic order, use the @JsonPropertyOrder annotation as follows:
@JsonPropertyOrder(alphabetic = true) public class LocationDTO { // fields.... }The response body will be like this:
{ "code": "MBMHR_IN", "city_name": "Mumbai", "enabled": true, "region_name": "Maharashtra", "country_name": "India", "country_code": "IN" }
Reference:
Annotation Type JsonPropertyOrder (Jackson Docs)
Related REST API Tutorials:
- Java RESTful Web Services Tutorial for Beginner with Jersey and Tomcat
- Java CRUD RESTful Web Services Examples with Jersey and Tomcat
- Spring Boot Hello World RESTful Web Services Tutorial
- Spring Boot RESTful CRUD API Examples with MySQL database
- Spring Boot File Download and Upload REST API Examples
- Spring Boot REST API CRUD with HATEOAS Tutorial
- How to Use curl for Testing REST APIs (Test CRUD Operations)
- How to Use Postman for Testing REST APIs (Test CRUD Operations)