sebastiandaschner blog


JSON-B Asymmetrical Property Binding

#javaee monday, august 20, 2018

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!

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: