Java has immense application in the coding world, and almost all of us know this fact. One of its features is the Jackson annotations. Although that is a very familiar term with the people involved in the coding world, it is less known. Jackson is a popular and very efficient JAVA library used to map or serialize JAVA objects to JSON and vice versa.
Since Jackson is a JAVA-based library, one must know the basics of JAVA before going on with Jackson. It provides various features that are listed as below:
- Jackson is an easy-to-use library that can simplify commonly used cases.
- Since it provides default mapping, there is no need to create a mapping in Jackson.
- It has a commendable speed and low memory footprint, making it suitable for large object systems.
- The JSON results created by Jackson are compact and clean, which makes them easy to read.
- Jdk is the only library that Jackson requires. Therefore, it has no dependency.
- Above all, the Jackson library is free to use since it is open-source.
After we have learned about the use and advantages of using Jackson, we now need to understand the Jackson annotations are as follows:
- @JsonAnyGetter
- @JsonGetter
- @JsonPropertyOrder
- @JsonRawValue
- @JsonValue
- @JsonRootName
- @JsonSerialize
- @JsonCreator
- @JacksonInject
- @JsonAnySetter
- @JsonSetter
- @JsonDeserialize
- @JsonEnumDefaultValue
- @JsonIgnoreProperties
- @JsonIgnore
- @JsonIgnoreType
- @JsonInclude
- @JsonAutoDetect
- @JsonTypeInfo
- @JsonSubTypes
- @JsonTypeName
- @JsonProperty
- @JsonFormat
- @JsonUnwrapped
- @JsonView
- @JsonManagedReference
- @JsonBackReference
- @JsonIdentityInfo
- @JsonFilter
- @JacksonAnnotationsInside
Let us discuss each of the annotations in order to understand them to deeper roots by implementing them providing fragment codes for all of them.
Annotation 1: @JsonAnyGetter
t facilitates a return of Maps using a getter method. Later the maps are used to serialize the additional properties of JSON in the same way as other properties.
public class ExtendableBean {
public String name;
private Map<String, String> properties;
@JsonAnyGetter
public Map<String, String> getProperties() {
return properties;
}
}
Annotation 2: @JsonGetter
This annotation facilitates the marking of a specific method as a getter method.
public class MyBean {
public int id;
private String name;
@JsonGetter("name")
public String getTheName() {
return name;
}
}
Annotation 3: @JsonPropertyOrder
While you serialize a JSON object, its order might change, but this annotation facilitates preserving a specific order while the process goes on.
@JsonPropertyOrder({ "name", "id" })
public class MyBean {
public int id;
public String name;
}
Annotation 4: @JsonRawValue
Using this annotation, one can serialize any word without any decoration or escape.
public class RawBean {
public String name;
@JsonRawValue
public String json;
}
Annotation 5: @JsonValue
Using this annotation, you can serialize an entire object using a single method.
public enum TypeEnumWithValue {
TYPE1(1, "Type A"), TYPE2(2, "Type 2");
private Integer id;
private String name;
// Standard constructors
@JsonValue
public String getName() {
return name;
}
}
Annotation 6: @JsonRootName
This annotation facilitates the appearance of a root node specified over JSON. Wrap root value also needs to be enabled.
{
"id": 1,
"name": "John"
}
Annotation 7: @JsonSerialize
Using this annotation, you can specify a custom serializer to marshall the JSON object.
public class EventWithSerializer {
public String name;
@JsonSerialize(using = CustomDateSerializer.class)
public Date eventDate;
}
Annotation 8: @JsonCreator
During deserialization, there is a factory method used. This annotation is used to fine-tune this method.
{
"id": 1,
"theName": "My bean"
}
Annotation 9: @JacksonInject
When we do not have to parse the property value, instead inject it in the JSON input, we use this annotation.
public class BeanWithInject {
@JacksonInject
public int id;
public String name;
}
Annotation 10: @JsonAnySetter
Just as the getter annotation, this facilitates a setter method for using Map, which is then used to deserialize the additional properties of JSON in the same manner as other properties.
public class ExtendableBean {
public String name;
private Map<String, String> properties;
@JsonAnySetter
public void add(String key, String value) {
properties.put(key, value);
}
}
Annotation 11: @JsonSetter
This annotation allows any method to be marked as a setter method.
public class MyBean {
public int id;
private String name;
@JsonSetter("name")
public void setTheName(String name) {
this.name = name;
}
}
Annotation 12: @JsonDeserialize
This annotation is used to specify a custom deserializer in order to unmarshall a JSON object.
public class EventWithSerializer {
public String name;
@JsonDeserialize(using = CustomDateDeserializer.class)
public Date eventDate;
}
Annotation 13: @JsonEnumDefaultValue
Using this annotation, we use a default value for deserializing an unknown enum value.
public class AliasBean {
@JsonAlias({ "fName", "f_name" })
private String firstName;
private String lastName;
}
Annotation 14: @JsonIgnoreProperties
Using this annotation, you can mark a property or a group of properties to be ignored. This is done at the class level.
@JsonIgnoreProperties({ "id" })
public class BeanWithIgnore {
public int id;
public String name;
}
Annotation 15: @JsonIgnore
This one serves the same purpose as above, the only difference being that it is used at the field level.
public class BeanWithIgnore {
@JsonIgnore
public int id;
public String name;
}
Annotation 16: @JsonIgnoreType
Using this annotation, you can mark the property of a specific type to be ignored.
public class User {
public int id;
public Name name;
@JsonIgnoreType
public static class Name {
public String firstName;
public String lastName;
}
}
Annotation 17: @JsonInclude
This annotation is used at those exclude properties that have null or empty default values.
@JsonInclude(Include.NON_NULL)
public class MyBean {
public int id;
public String name;
}
Annotation 18: @JsonAutoDetect
This annotation helps detect properties that are not visible or accessible otherwise.
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class PrivateBean {
private int id;
private String name;
}
Annotation 19: @JsonTypeInfo
Using this annotation, you can indicate the details of the type of information that has to be included either during serialization or deserialization.
Annotation 20: @JsonSubTypes
This one is used to indicate the subtypes of the types that have been annotated.
Annotation 21: @JsonTypeName
Using this one can set type names that have to be used for annotated classes.
public class Zoo {
public Animal animal;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Dog.class, name = "dog"),
@JsonSubTypes.Type(value = Cat.class, name = "cat")
})
public static class Animal {
public String name;
}
@JsonTypeName("dog")
public static class Dog extends Animal {
public double barkVolume;
}
@JsonTypeName("cat")
public static class Cat extends Animal {
boolean likesCream;
public int lives;
}
}
Annotation 22: @JsonProperty
This annotation is used to mark the non-standard setter or getter methods that have to be used concerning JSON properties.
public class MyBean {
public int id;
private String name;
@JsonProperty("name")
public void setTheName(String name) {
this.name = name;
}
@JsonProperty("name")
public String getTheName() {
return name;
}
}
Annotation 23: @JsonFormat
This annotation is usually used in Date fields and specifies the format during serialization or deserialization.
public class EventWithFormat {
public String name;
@JsonFormat(
shape = JsonFormat.Shape.STRING,
pattern = "dd-MM-yyyy hh:mm:ss")
public Date eventDate;
}
Annotation 24: @JsonUnwrapped
During the process of serialization or deserialization, it is required to unwrap the values of objects. This annotation is used to fulfill the purpose.
public class UnwrappedUser {
public int id;
@JsonUnwrapped
public Name name;
public static class Name {
public String firstName;
public String lastName;
}
}
Annotation 25: @JsonView
This annotation is used to control the values to be serialized or not.
public class Views {
public static class Public {}
public static class Internal extends Public {}
}
Annotation 26: @JsonManagedReference
Such annotations are used for the display of objects with a parent-child relationship.
public class ItemWithRef {
public int id;
public String itemName;
@JsonManagedReference
public UserWithRef owner;
}
Annotation 27: @JsonBackReference
This shares the same function as the previous one.
private class Player {
public int id;
public Info info;
}
private class Info {
public int id;
public Player parentPlayer;
}
// Something like this will come into play
Player player = new Player(1);
player.info = new Info(1, player);
Annotation 28: @JsonIdentityInfo
This annotation is used in a case where there is a parent-child relationship. It is used to indicate that an object identity will be used during serialization and deserialization.
Java
@JsonIdentityInfo (
generator = ObjectIdGenerators.PropertyGenerator. class ,
property = "id" )
public class ItemWithIdentity {
public int id;
public String itemName;
public UserWithIdentity owner;
}
|
Annotation 29: @JsonFilter
This annotation can be used to apply filters during the process of serialization and deserialization.
@JsonFilter("myFilter")
public class BeanWithFilter {
public int id;
public String name;
}
Annotation 30: @JacksonAnnotationsInside
This annotation can be used to create customized Jackson annotations.
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonInclude(Include.NON_NULL)
@JsonPropertyOrder({ "name", "id", "dateCreated" })
public @interface CustomAnnotation {}
Note: Various other annotations are used to rename properties or ignore them or choose the more or less specific types.
While using these annotations, Jackson itself uses the default constructors while creating value instances. However, one may alter it by putting the customize constructor. Also, Jackson can handle polymorphic types, that is, objects with various subtypes. This does by enabling the inclusion of type information. Therefore, these were a few points and essential information on the Jackson annotations, their use, and their importance in Java.
Share your thoughts in the comments
Please Login to comment...