News Ticker

JSON Binding 1.0 API: 100DaysOfJavaEE8

JSON-B 1.0 Challenge

JSON Binding allows fine grain control over the order in which JSON properties appear. Runtime and compile customization can be used to control this features.

Given an instance of the Book class and the JSON Binding code below, which of the four JSON document is produced?

Answer

The JSON document produced is 2: It follows the order specified in the  @JsonbPropertyOrder annotation.

Explanation

The JSON Binding API provides excellent customization options the allow the default behavior of property ordering to be configured. This can be done via runtime configurations by setting the PropertyOrderStrategy on an instance of JsonbConfig and passing it to the JsonbBuilder. Alternatively, the order can be explicitly specified with the class level compile time annotation @JsonbPropertyOrder. The order of the properties in the JSON document reflects the order in which they appear in the property list passed to the annotation.

The question is if both methods are used together which one has precedence? The answer is the annotation. So the order of the properties in the Book JSON document is as shown in the list  value = {“authorName”, “bookPrice”, “bookTitle”}. Any properties not specified in that list are ordered according to the strategy set by PropertyOrderStrategy.

Further Reading

For further information on how to use the new JSON Binding API take a look at my new book Java EE 8: Only What’s New and also you should read the specifications for the Java API for JSON Binding (JSR 367).

GitHub Repository

The code from this and all other #100DaysOfJavaEE8 can be found in my GitHub repository.

Leave a Reply

Discover more from Digital Transformation and Java Video Training

Subscribe now to keep reading and get access to the full archive.

Continue reading