Filters are one of the important features provided by the JAX-RS framework. It is used in various contexts. It may be applied on either request to a resource or the response from a resource, or both.Consider a scenario in which we do not want to show some class members in the response. This process is called filtering. Jackson has two annotations that are used in filtering are: @JsonIgnore and @JsonIgnoreProperties.
@JsonIgnore is used at field level to mark a property or list of properties to be ignored.
import java.io.IOException; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonSampleTest { public static void main(String args[]){ ObjectMapper mapper = new ObjectMapper(); try{ Student student = new Student(1,11,"LABORATORY","SAMUEL"); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); } } } class Student { public int id; @JsonIgnore public String systemId; public int rollNo; public String name; Student(int id, int rollNo, String systemId, String name){ this.id = id; this.systemId = systemId; this.rollNo = rollNo; this.name = name; } }
{ "id" : 1, "rollNo" : 11, "name" : "SAMUEL" }
@JsonIgnore is a member or method level annotation. It expects that the properties to be excluded are marked one by one. If we want to eliminate a member from the process of serialization and deserialization, we can annotate the actual property or its setter or getter.
@JsonIgnoreProperties is a class-level annotation. It ignores the logical properties in JSON serialization and deserialization.
Comments
Post a Comment