Enterprise Java

JSON-B Asymmetrical Property Binding

The JSON-B specification defines binding annotations such as @JsonbProperty or @JsonbTransient to declaratively map Java objects to JSON, and back. These annotations can be used ‘asymmetrically’ to define different handling of serialization and deserialization.

If JSON Binding annotations are annotated on Java properties, or on both getters and setters, they will control how the objects are serialized and deserialized. If they are only defined on either the getter or the setter, the behavior will only take action for either serialization or deserialization, respectively. The binding definitions for multiple properties can be mixed and matched within a single class.

See the following example:

public class Account {

    private long id;

    // will always map name to testName
    @JsonbProperty("testName")
    private String name;

    // will serialize id to JSON
    public long getId() {
        return id;
    }

    // will not deserialize id from JSON
    @JsonbTransient
    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Happy asymmetrical JSON binding!

Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: JSON-B Asymmetrical Property Binding

Opinions expressed by Java Code Geeks contributors are their own.

Sebastian Daschner

Sebastian Daschner is a self-employed Java consultant and trainer. He is the author of the book 'Architecting Modern Java EE Applications'. Sebastian is a Java Champion, Oracle Developer Champion and JavaOne Rockstar.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button