JSON-B Asymmetrical Property Binding [Snippet]
Let's take a brief look at how you can use the JSON-B specification to quickly and easily map Java objects to JSON and back again.
Join the DZone community and get the full member experience.
Join For FreeThe 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 the 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 at DZone with permission of Sebastian Daschner. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments