Implementing Static Filtering for Rest API
Customize Rest Api Responses - Filtering and More..
Serialization: convert object into stream (Example JSON)
Example we are Return like
we are getting back EntityModel in below method
public EntityModel<User> getUsers() {}
we are getting back List of User in below method
public List<User> getAllUsers() {}
Converting into a Json or to an XML is what is called serialization
Most Popular JSON serialization in Java Is Jackson
- How About customize the REST Api response returned by Jackson Framewor
- 1: Customize Field name in response
- @JSONProperty
public class User {
private Integer id;
@Size(min = 2, message = "Name min size is 2 atleast")
@JsonProperty("user_name")
private String name;
@Past(message = "birthDate should be lessthan from todays date")
@JsonProperty("birth_date")
private LocalDate birthDate;
@Pattern(regexp = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$", message = "email in not in proepr format")
private String emailID;
//getter setter
}
Output:
- 2: Return Only Selected Fields
- Filtering
- Example: Filtering out the passwords
- Two Types: of Filtering
- Static Filtering: Same Filtering for a bean across different REST API
- @JsonIgnoreProperties, @JsonIgnore
- Dynamic Filtering: Customize filtering for abean for specific REST API
- @JsonFilter with filterProvider
Static Filtering:
SomeBean.java
public class SomeBean {
private String field1;
@JsonIgnore
private String field2;
private String field3;
//getter & Constructor
}
FilteringController.java
@RestController
public class FilteringController {
@GetMapping("/filtering")
public SomeBean filtering() {
return new SomeBean("value1", "value2", "value3");
}
}
O/P
{ "field1": "value1", "field3": "value3" }
as in given avobe example we have filter out the field2 so now oly
1 and 3 field will be in json Output
also
Comments
Post a Comment