@JsonPropertyOrder annotation use to define the order of JSON properties while serialization from Java to JSON. This annotation always use on class level.
@JsonPropertyOrder on Class Level
@JsonPropertyOrder({"firstName","lastName","rollNumber"}) public class StudentDetail { @JsonProperty(value = "id") private int rollNumber; @JsonProperty(value = "firstName") private String first_name; @JsonProperty(value = "lastName") private String last_name; }
Here you will see complete example of JSON properties name change and define order of JSON propertis.
Complete Example
@JsonPropertyOrder({"firstName","lastName","rollNumber"}) public class StudentDetail { @JsonProperty(value = "id") private int rollNumber; @JsonProperty(value = "firstName") private String first_name; @JsonProperty(value = "middleName") private String middle_name; @JsonProperty(value = "lastName", index=1) private String last_name; public StudentDetail() { } //Getter and Setter //toString() method }
Code to convert Java object to JSON.
public class JsonPropertiesOrder { public static void main(String [] args) { StudentDetail student=new StudentDetail(); student.setFirst_name("Saurabh"); student.setRollNumber(25); student.setLast_name("Gupta"); System.out.println(student); try { // ObjectMapper new instance ObjectMapper objectMapper = new ObjectMapper(); // configure Object mapper for pretty print objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); // writing to console, can write to any output stream such as file String json =objectMapper.writeValueAsString(student); System.out.println(json); } catch (JsonMappingException ex) { ex.printStackTrace(); } catch (JsonGenerationException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }
Output
StudentDetail [rollNumber=25, firstName=Saurabh, lastName=Gupta]
{
"firstName" : "Saurabh",
"lastName" : "Gupta",
"id" : 25
}
References
https://github.com/FasterXML/jackson-annotations
You would like to see
Follow below link to learn more on JSON and JSON issues solutions:
You must be logged in to post a comment.