Friday, 14 January 2022

Define custom Jackson annotation using @JacksonAnnotationsInside

You can define custom Jackson annotation using @JacksonAnnotationsInside. @JacksonAnnotationsInside is a meta-annotation used to create a "combo-annotations" by having a container annotation, which needs to be annotated with this annotation as well as all annotations it 'contains'.

Example



Find the below working application. 

AppJSON.java

package com.sample.app.jackson;

import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public @interface AppJSON {
	
}

Employee.java

package com.sample.app.model;

import com.sample.app.jackson.AppJSON;

@AppJSON
public class Employee {
	private Integer id;
	private String name;
	private Integer age;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

}

App.java

package com.sample.app.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.app.model.Employee;

public class App {

	public static void main(String args[]) throws JsonProcessingException {
		Employee emp = new Employee();
		emp.setId(1);
		emp.setName("Krishna");
		
		String result = new ObjectMapper().writeValueAsString(emp);
		System.out.println(result);
	}
}

Output

{"id":1,"name":"Krishna"}


Previous                                                    Next                                                    Home

No comments:

Post a Comment