Spring boot validation for interfaces and extended ArrayList - java

I am using spring-boot with hibernate validator
I have a controller annotated with #Validated and I want to validate all the params in my APIs.
One of the annotation is not working(I debugged and it just never being checked as if it is not annotated at all).
public MyResponse getPolicyCounters(#RequestBody #Valid MyRequest request) throws Exception {
The MyRequest class looks like this:
#Valid
public class MyRequest{
boolean shouldSumSubRules;
private #Valid RulesSelector rules;
The RuleSelector class is an interface and looks like this:
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
#JsonSubTypes({
#JsonSubTypes.Type(value = RulesStaticList.class, name = "list"),
#JsonSubTypes.Type(value = RulesDynamicList.class, name = "criteria")
})
#Valid
public interface RulesSelector {
}
The RuleStaticList class looks like this:
#Valid
public class RulesStaticList extends ArrayList<#Valid RuleReference> implements RulesSelector {
}
The RuleRefrence class looks like this:
#JsonDeserialize(using = RuleReferenceDeserializer.class)
#Valid
public interface RuleReference {
RuleReferenceKind getKind();
}
final class RuleReferenceDeserializer extends StdDeserializer<RuleReference> {
public RuleReferenceDeserializer() {
super(RuleReference.class);
}
#Override
public RuleReference deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String fieldName = p.nextFieldName();
switch (fieldName) {
case "tag":
return p.readValueAs(RuleReferenceByTag.class);
case "special":
return p.readValueAs(RuleReferenceBySpecial.class);
default:
throw ctxt.wrongTokenException(p, RuleReference.class, JsonToken.FIELD_NAME, "");
}
}
}
I have 2 implementation for RuleReference one of them is RuleReferenceByTag and it looks like this:
#Valid
public class RuleReferenceByTag implements RuleReference {
#Size(max = 128)
private String tag;
public RuleReferenceKind getKind() { return RuleReferenceKind.Tag; }
}
I added #Valid annotation everywhere I could but it still does not work.
What am I missing?
Other annotation in with different classes it does work but I could not solve this problem :/

Related

How I can make RequestParam dynamic?

I have a list of POST requests, where request bodies are quite similar
{
"entity":{
"type":"Nissan"
"parts":{
"Nissan_unique_content1":"value",
"Nissan_unique_content2":"value"
}
}
"updateDate":"Date..."
}
{
"entity":{
"type":"Ford"
"parts":{
"Ford_unique_content1":"value",
"Ford_unique_content2":"value",
"Ford_unique_content3":"value"
}
}
"updateDate":"Date..."
}
I have a generic RequestBody
public class RequestBody<T>{
EntityBody<T> entity;
Date updateDate;
}
public class EntityBody<T>{
String type;
T parts;
}
In my Post Controller I have method as
#RequestMapping(value = "/{type}")
public ResponseEntity<?> create(
#PathVariable(value = "type") String type,
#RequestBody RequestBody<T> body) {
...
}
Is there anyway that generic type T can be assigned depends on type?
In this case I wouldn't need create multiple create method, otherwise I need create multiple method, like
#RequestMapping(value = "/nissan")
public ResponseEntity<?> createNissan(
#RequestBody RequestBody<NissanContent> body) {
...
}
#RequestMapping(value = "/ford")
public ResponseEntity<?> createFord(
#RequestBody RequestBody<Ford> body) {
...
}
which are unnecessary repetitions.
This can be done by using #JsonTypeInfo annotation.
For example:
Define entities according to different structures under "parts" key:
class NissanParams {
#JsonProperty("Nissan_unique_content1")
private String nissanUniqueContent1;
#JsonProperty("Nissan_unique_content2")
private String nissanUniqueContent2;
// getters + setters
}
In EntityBody, remove type field and add the annotations:
public class EntityBody<T> {
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type")
#JsonSubTypes({ #JsonSubTypes.Type(value = NissanParams.class, name = "Nissan")})
private T parts;
}
And there will be a single controller method:
#PostMapping(path = "{make}",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public RequestBody<Object> create(#PathVariable("make") String make,
#org.springframework.web.bind.annotation.RequestBody RequestBody<Object> body) {
// please change the name of "RequestBody" entity, in order to avoid name clash with the annotation
}
You can use JsonTypeInfo and JsonSubTypes Jackson annotations. Your model could look like:
class EntityBody {
private Car parts;
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
#JsonSubTypes({
#JsonSubTypes.Type(name = "Ford", value = Ford.class),
#JsonSubTypes.Type(name = "Nissan", value = Nissan.class)
})
public Car getParts() {
return parts;
}
}
As you can see, you do not need type property. It will be read by Jackson to find out a car type. I have created Car base class/interface but you do not need to do that.
Your POST method could look like this:
#RequestMapping(value = "/cars", method = RequestMethod.POST)
public ResponseEntity<?> create(#RequestBody RequestPayload body) {
logger.info(body.toString());
return ResponseEntity.ok("OK");
}
You do not need PathVariable here.

#JsonView with Spring PagedResources

I've a pojo exposed with Rest Controller. I need to hide some properties for one GET request, so I decided to use jackson's annotation #JsonView. I can't find any way to made it with #JsonView and PagedResources.
Here is my pojo :
public class Pojo {
interface RestrictedPojo {}
interface AllPojo extends RestrictedPojo {}
#Id
#JsonView(RestrictedPojo.class)
private String identifier;
#JsonView(AllPojo.class)
private String someproperty;
/**
* Property I want to hide
*/
#JsonView(RestrictedPojo.class)
private String someHiddenProperty;
}
Here is my Controller :
#RepositoryRestController
#RequestMapping(value = "/pojo")
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class PojoController {
private final PojoService pojoService;
private final IdentityUtils identityUtils;
private final PagedResourcesAssembler<Pojo> pagedResourcesAssembler;
#PreAuthorize("hasRole('SOME_ROLE')")
#GetMapping
#JsonView(Pojo.RestrictedPojo.class)
public ResponseEntity<PagedResources<Resource<Pojo>>> getAllRestrictedPojos(final Pageable pageable) {
final Page<Pojo> allPojo = pojoService.getAllRestrictedPojos(pageable);
final PagedResources<Resource<Pojo>> resources = pagedResourcesAssembler.toResource(allPojo );
return ResponseEntity.ok(resources);
}
#PreAuthorize("hasRole('SOME_ROLE')")
#GetMapping
#JsonView(Pojo.AllPojo.class)
public ResponseEntity<PagedResources<Resource<Pojo>>> getAllPojos(final Pageable pageable) {
final Page<Pojo> allPojo = pojoService.getAllRestrictedPojos(pageable);
final PagedResources<Resource<Pojo>> resources = pagedResourcesAssembler.toResource(allPojo );
return ResponseEntity.ok(resources);
}
}
I didn't wrote specific config, it's a basic spring boot app.
Can anyone help ?
Thanks

How to deserialize JSON to interface?

I have trouble with deserialization JSON to some of classes ChildA, ChildB and etc. that implements Basic interface in following example.
#JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(value = InstagramUser.class, name = "ChildA")
})
public interface Basic {
getName();
getCount();
}
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonTypeName("ChildA")
public class ChildA implements Basic { ... }
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonTypeName("ChildB")
public class ChildB implements Basic { ... }
...
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Response<E extends Basic> {
#JsonProperty("data")
private List<E> data;
public List<E> getData() {
return data;
}
public void setData(List<E> data) {
this.data = data;
}
}
// deserialization
HTTPClient.objectMapper.readValue(
response,
(Class<Response<ChildA>>)(Class<?>) Response.class
)
Exception is: com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'type' that is to contain type id (for class Basic)
Expected JSON is like this:
{
"data": [{ ... }, ...]
}
There is no property that is presented in all type objects so they are completely different. But as you can see on readValue line I know what is expected type. How to structure JsonTypeInfo and JsonSubTypes annotaions to deserialize JSON as expected class?
I kinda had the same problem as you, based in the reading here: Jackson Deserialize Abstract Classes I created my own solution, it basically consists of creating my own deserializer, the trick is to use/identify a specific property within JSON to know which instance type should be returned from deserialization, example is:
public interface Basic {
}
First Child:
public class ChildA implements Basic {
private String propertyUniqueForThisClass;
//constructor, getters and setters ommited
}
SecondChild:
public class ChildB implements Basic {
private String childBUniqueProperty;
//constructor, getters and setters ommited
}
The deserializer (BasicDeserializer.java) would be like:
public class BasicDeserializer extends StdDeserializer<Basic> {
public BasicDeserializer() {
this(null);
}
public BasicDeserializer(final Class<?> vc) {
super(vc);
}
#Override
public Basic deserialize(final JsonParser jsonParser,
final DeserializationContext deserializationContext)
throws IOException {
final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
final ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
// look for propertyUniqueForThisClass property to ensure the message is of type ChildA
if (node.has("propertyUniqueForThisClass")) {
return mapper.treeToValue(node, ChildA.class);
// look for childBUniqueProperty property to ensure the message is of type ChildB
} else if (node.has("childBUniqueProperty")) {
return mapper.treeToValue(node, ChildB.class);
} else {
throw new UnsupportedOperationException(
"Not supported class type for Message implementation");
}
}
}
Finally, you'd have an utility class (BasicUtils.java):
private static final ObjectMapper MAPPER;
// following good software practices, utils can not have constructors
private BasicUtils() {}
static {
final SimpleModule module = new SimpleModule();
MAPPER = new ObjectMapper();
module.addDeserializer(Basic.class, new BasicDeserializer());
MAPPER.registerModule(module);
}
public static String buildJSONFromMessage(final Basic message)
throws JsonProcessingException {
return MAPPER.writeValueAsString(message);
}
public static Basic buildMessageFromJSON(final String jsonMessage)
throws IOException {
return MAPPER.readValue(jsonMessage, Basic.class);
}
For testing:
#Test
public void testJsonToChildA() throws IOException {
String message = "{\"propertyUniqueForThisClass\": \"ChildAValue\"}";
Basic basic = BasicUtils.buildMessageFromJSON(message);
assertNotNull(basic);
assertTrue(basic instanceof ChildA);
System.out.println(basic);
}
#Test
public void testJsonToChildB() throws IOException {
String message = "{\"childBUniqueProperty\": \"ChildBValue\"}";
Basic basic = BasicUtils.buildMessageFromJSON(message);
assertNotNull(basic);
assertTrue(basic instanceof ChildB);
System.out.println(basic);
}
The source code can be found on: https://github.com/darkstar-mx/jsondeserializer
I find not exactly solution but a workaround. I used custom response class ChildAResponse and passed it to ObjectMapper.readValue() method.
class ChildAResponse extends Response<ChildA> {}
// deserialization
HTTPClient.objectMapper.readValue(
response,
ChildAResponse.class
)
So JsonTypeInfo and JsonSubTypes annotations on the interface are no longer needed.

Spring #RestController custom JSON deserializer

I want to use custom JSON deserializer for some classes(Role here) but I can't get it working. The custom deserializer just isn't called.
I use Spring Boot 1.2.
Deserializer:
public class ModelDeserializer extends JsonDeserializer<Role> {
#Override
public Role deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return null; // this is what should be called but it isn't
}
}
Controller:
#RestController
public class RoleController {
#RequestMapping(value = "/role", method = RequestMethod.POST)
public Object createRole(Role role) {
// ... this is called
}
}
#JsonDeserialize on Role
#JsonDeserialize(using = ModelDeserializer.class)
public class Role extends Model {
}
Jackson2ObjectMapperBuilder bean in Java Config
#Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.deserializerByType(Role.class, new ModelDeserializer());
return builder;
}
What am I doing wrong?
EDIT It is probably caused by #RestController because it works with #Controller...
First of all you don't need to override Jackson2ObjectMapperBuilder to add custom deserializer. This approach should be used when you can't add #JsonDeserialize annotation. You should use #JsonDeserialize or override Jackson2ObjectMapperBuilder.
What is missed is the #RequestBody annotation:
#RestController
public class JacksonCustomDesRestEndpoint {
#RequestMapping(value = "/role", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public Object createRole(#RequestBody Role role) {
return role;
}
}
#JsonDeserialize(using = RoleDeserializer.class)
public class Role {
// ......
}
public class RoleDeserializer extends JsonDeserializer<Role> {
#Override
public Role deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// .................
return something;
}
}
There is also another pretty interesting solution which can be helpful in case when you want to modify your JSON body before calling default deserializer. And let's imagine that you need to use some additional bean for that (use #Autowire mechanism)
Let's image situation, that you have the following controller:
#RequestMapping(value = "/order/product", method = POST)
public <T extends OrderProductInterface> RestGenericResponse orderProduct(#RequestBody #Valid T data) {
orderService.orderProduct(data);
return generateResponse();
}
Where OrderProductInterface is:
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonSerialize(include = NON_EMPTY)
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, visible = true, property = "providerType")
#JsonSubTypes({
#JsonSubTypes.Type(value = OrderProductForARequestData.class, name = "A")
})
public interface OrderProductInterface{}
The code above will provide dynamic deserialization base on filed providerType and validation according to concrete implementation. For better grasp, consider that OrderProductForARequestData can be something like that:
public class OrderProductForARequestData implements OrderProductInterface {
#NotBlank(message = "is mandatory field.")
#Getter #Setter
private String providerId;
#NotBlank(message = "is mandatory field.")
#Getter #Setter
private String providerType;
#NotBlank(message = "is mandatory field.")
#Getter #Setter
private String productToOrder;
}
And let's image now that we want to init somehow providerType (enrich input) before default deserialization will be executed. so the object will be deserialized properly according to the rule in OrderProductInterface.
To do that you can just modify your #Configuration class in the following way:
//here can be any annotation which will enable MVC/Boot
#Configuration
public class YourConfiguration{
#Autowired
private ObjectMapper mapper;
#Autowired
private ProviderService providerService;
#Override
public void setup() {
super.setup();
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new BeanDeserializerModifier() {
#Override
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
if (beanDesc.getBeanClass() == OrderProductInterface.class) {
return new OrderProductInterfaceDeserializer(providerService, beanDesc);
}
return deserializer;
}
});
mapper.registerModule(module);
}
public static class OrderProductInterfaceDeserializer extends AbstractDeserializer {
private static final long serialVersionUID = 7923585097068641765L;
private final ProviderService providerService;
OrderProductInterfaceDeserializer(roviderService providerService, BeanDescription beanDescription) {
super(beanDescription);
this.providerService = providerService;
}
#Override
public Object deserializeWithType(JsonParser p, DeserializationContext context, TypeDeserializer typeDeserializer) throws IOException {
ObjectCodec oc = p.getCodec();
JsonNode node = oc.readTree(p);
//Let's image that we have some identifier for provider type and we want to detect it
JsonNode tmp = node.get("providerId");
Assert.notNull(tmp, "'providerId' is mandatory field");
String providerId = tmp.textValue();
Assert.hasText(providerId, "'providerId' can't be empty");
// Modify node
((ObjectNode) node).put("providerType",providerService.getProvider(providerId));
JsonFactory jsonFactory = new JsonFactory();
JsonParser newParser = jsonFactory.createParser(node.toString());
newParser.nextToken();
return super.deserializeWithType(newParser, context, typeDeserializer);
}
}
}

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

I have model class like this, for hibernate
#Entity
#Table(name = "user", catalog = "userdb")
#JsonIgnoreProperties(ignoreUnknown = true)
public class User implements java.io.Serializable {
private Integer userId;
private String userName;
private String emailId;
private String encryptedPwd;
private String createdBy;
private String updatedBy;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "UserId", unique = true, nullable = false)
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
#Column(name = "UserName", length = 100)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "EmailId", nullable = false, length = 45)
public String getEmailId() {
return this.emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
#Column(name = "EncryptedPwd", length = 100)
public String getEncryptedPwd() {
return this.encryptedPwd;
}
public void setEncryptedPwd(String encryptedPwd) {
this.encryptedPwd = encryptedPwd;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "UpdatedBy", length = 100)
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
In Spring MVC controller, using DAO, I am able to get the object. and returning as JSON Object.
#Controller
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
#ResponseBody
public User getUser(#PathVariable Integer userId) throws Exception {
User user = userService.get(userId);
user.setCreatedBy(null);
user.setUpdatedBy(null);
return user;
}
}
View part is done using AngularJS, so it will get JSON like this
{
"userId" :2,
"userName" : "john",
"emailId" : "john#gmail.com",
"encryptedPwd" : "Co7Fwd1fXYk=",
"createdBy" : null,
"updatedBy" : null
}
If I don't want to set encrypted Password, I will set that field also as null.
But I don't want like this, I dont want to send all fields to client side. If I dont want password, updatedby, createdby fields to send, My result JSON should be like
{
"userId" :2,
"userName" : "john",
"emailId" : "john#gmail.com"
}
The list of fields which I don't want to send to client coming from other database table. So it will change based on the user who is logged in. How can I do that?
I hope You got my question.
Add the #JsonIgnoreProperties("fieldname") annotation to your POJO.
Or you can use #JsonIgnore before the name of the field you want to ignore while deserializing JSON. Example:
#JsonIgnore
#JsonProperty(value = "user_password")
public String getUserPassword() {
return userPassword;
}
GitHub example
Can I do it dynamically?
Create view class:
public class View {
static class Public { }
static class ExtendedPublic extends Public { }
static class Internal extends ExtendedPublic { }
}
Annotate you model
#Document
public class User {
#Id
#JsonView(View.Public.class)
private String id;
#JsonView(View.Internal.class)
private String email;
#JsonView(View.Public.class)
private String name;
#JsonView(View.Public.class)
private Instant createdAt = Instant.now();
// getters/setters
}
Specify the view class in your controller
#RequestMapping("/user/{email}")
public class UserController {
private final UserRepository userRepository;
#Autowired
UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
#RequestMapping(method = RequestMethod.GET)
#JsonView(View.Internal.class)
public #ResponseBody Optional<User> get(#PathVariable String email) {
return userRepository.findByEmail(email);
}
}
Data example:
{"id":"5aa2496df863482dc4da2067","name":"test","createdAt":"2018-03-10T09:35:31.050353800Z"}
UPD: keep in mind that it's not best practice to use entity in response. Better use different DTO for each case and fill them using modelmapper
I know I'm a bit late to the party, but I actually ran into this as well a few months back. All of the available solutions weren't very appealing to me (mixins? ugh!), so I ended up creating a new library to make this process cleaner. It's available here if anyone would like to try it out: https://github.com/monitorjbl/spring-json-view.
The basic usage is pretty simple, you use the JsonView object in your controller methods like so:
import com.monitorjbl.json.JsonView;
import static com.monitorjbl.json.Match.match;
#RequestMapping(method = RequestMethod.GET, value = "/myObject")
#ResponseBody
public void getMyObjects() {
//get a list of the objects
List<MyObject> list = myObjectService.list();
//exclude expensive field
JsonView.with(list).onClass(MyObject.class, match().exclude("contains"));
}
You can also use it outside of Spring:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import static com.monitorjbl.json.Match.match;
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
mapper.writeValueAsString(JsonView.with(list)
.onClass(MyObject.class, match()
.exclude("contains"))
.onClass(MySmallObject.class, match()
.exclude("id"));
Yes, you can specify which fields are serialized as JSON response and which to ignore.
This is what you need to do to implement Dynamically ignore properties.
1) First, you need to add #JsonFilter from com.fasterxml.jackson.annotation.JsonFilter on your entity class as.
import com.fasterxml.jackson.annotation.JsonFilter;
#JsonFilter("SomeBeanFilter")
public class SomeBean {
private String field1;
private String field2;
private String field3;
// getters/setters
}
2) Then in your controller, you have to add create the MappingJacksonValue object and set filters on it and in the end, you have to return this object.
import java.util.Arrays;
import java.util.List;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
#RestController
public class FilteringController {
// Here i want to ignore all properties except field1,field2.
#GetMapping("/ignoreProperties")
public MappingJacksonValue retrieveSomeBean() {
SomeBean someBean = new SomeBean("value1", "value2", "value3");
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("field1", "field2");
FilterProvider filters = new SimpleFilterProvider().addFilter("SomeBeanFilter", filter);
MappingJacksonValue mapping = new MappingJacksonValue(someBean);
mapping.setFilters(filters);
return mapping;
}
}
This is what you will get in response:
{
field1:"value1",
field2:"value2"
}
instead of this:
{
field1:"value1",
field2:"value2",
field3:"value3"
}
Here you can see it ignores other properties(field3 in this case) in response except for property field1 and field2.
Hope this helps.
We can do this by setting access to JsonProperty.Access.WRITE_ONLY while declaring the property.
#JsonProperty( value = "password", access = JsonProperty.Access.WRITE_ONLY)
#SerializedName("password")
private String password;
Add #JsonInclude(JsonInclude.Include.NON_NULL) (forces Jackson to serialize null values) to the class as well as #JsonIgnore to the password field.
You could of course set #JsonIgnore on createdBy and updatedBy as well if you always want to ignore then and not just in this specific case.
UPDATE
In the event that you do not want to add the annotation to the POJO itself, a great option is Jackson's Mixin Annotations. Check out the documentation
I've solved using only #JsonIgnore like #kryger has suggested.
So your getter will become:
#JsonIgnore
public String getEncryptedPwd() {
return this.encryptedPwd;
}
You can set #JsonIgnore of course on field, setter or getter like described here.
And, if you want to protect encrypted password only on serialization side (e.g. when you need to login your users), add this #JsonProperty annotation to your field:
#JsonProperty(access = Access.WRITE_ONLY)
private String encryptedPwd;
More info here.
If I were you and wanted to do so, I wouldn't use my User entity in Controller layer.Instead I create and use UserDto (Data transfer object) to communicate with business(Service) layer and Controller.
You can use Apache BeanUtils(copyProperties method) to copy data from User entity to UserDto.
I have created a JsonUtil which can be used to ignore fields at runtime while giving a response.
Example Usage :
First argument should be any POJO class (Student) and ignoreFields is comma seperated fields you want to ignore in response.
Student st = new Student();
createJsonIgnoreFields(st,"firstname,age");
import java.util.logging.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
public class JsonUtil {
public static String createJsonIgnoreFields(Object object, String ignoreFields) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(Object.class, JsonPropertyFilterMixIn.class);
String[] ignoreFieldsArray = ignoreFields.split(",");
FilterProvider filters = new SimpleFilterProvider()
.addFilter("filter properties by field names",
SimpleBeanPropertyFilter.serializeAllExcept(ignoreFieldsArray));
ObjectWriter writer = mapper.writer().withFilters(filters);
return writer.writeValueAsString(object);
} catch (Exception e) {
//handle exception here
}
return "";
}
public static String createJson(Object object) {
try {
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
return writer.writeValueAsString(object);
}catch (Exception e) {
//handle exception here
}
return "";
}
}
I've found a solution for me with Spring and jackson
First specify the filter name in the entity
#Entity
#Table(name = "SECTEUR")
#JsonFilter(ModelJsonFilters.SECTEUR_FILTER)
public class Secteur implements Serializable {
/** Serial UID */
private static final long serialVersionUID = 5697181222899184767L;
/**
* Unique ID
*/
#Id
#JsonView(View.SecteurWithoutChildrens.class)
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#JsonView(View.SecteurWithoutChildrens.class)
#Column(name = "code", nullable = false, length = 35)
private String code;
/**
* Identifiant du secteur parent
*/
#JsonView(View.SecteurWithoutChildrens.class)
#Column(name = "id_parent")
private Long idParent;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name = "id_parent")
private List<Secteur> secteursEnfants = new ArrayList<>(0);
}
Then you can see the constants filters names class with the default FilterProvider used in spring configuration
public class ModelJsonFilters {
public final static String SECTEUR_FILTER = "SecteurFilter";
public final static String APPLICATION_FILTER = "ApplicationFilter";
public final static String SERVICE_FILTER = "ServiceFilter";
public final static String UTILISATEUR_FILTER = "UtilisateurFilter";
public static SimpleFilterProvider getDefaultFilters() {
SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAll();
return new SimpleFilterProvider().setDefaultFilter(theFilter);
}
}
Spring configuration :
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = "fr.sodebo")
public class ApiRootConfiguration extends WebMvcConfigurerAdapter {
#Autowired
private EntityManagerFactory entityManagerFactory;
/**
* config qui permet d'éviter les "Lazy loading Error" au moment de la
* conversion json par jackson pour les retours des services REST<br>
* on permet à jackson d'acceder à sessionFactory pour charger ce dont il a
* besoin
*/
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
// config d'hibernate pour la conversion json
mapper.registerModule(getConfiguredHibernateModule());//
// inscrit les filtres json
subscribeFiltersInMapper(mapper);
// config du comportement de json views
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
converter.setObjectMapper(mapper);
converters.add(converter);
}
/**
* config d'hibernate pour la conversion json
*
* #return Hibernate5Module
*/
private Hibernate5Module getConfiguredHibernateModule() {
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Hibernate5Module module = new Hibernate5Module(sessionFactory);
module.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, true);
return module;
}
/**
* inscrit les filtres json
*
* #param mapper
*/
private void subscribeFiltersInMapper(ObjectMapper mapper) {
mapper.setFilterProvider(ModelJsonFilters.getDefaultFilters());
}
}
Endly I can specify a specific filter in restConstoller when i need....
#RequestMapping(value = "/{id}/droits/", method = RequestMethod.GET)
public MappingJacksonValue getListDroits(#PathVariable long id) {
LOGGER.debug("Get all droits of user with id {}", id);
List<Droit> droits = utilisateurService.findDroitsDeUtilisateur(id);
MappingJacksonValue value;
UtilisateurWithSecteurs utilisateurWithSecteurs = droitsUtilisateur.fillLists(droits).get(id);
value = new MappingJacksonValue(utilisateurWithSecteurs);
FilterProvider filters = ModelJsonFilters.getDefaultFilters().addFilter(ModelJsonFilters.SECTEUR_FILTER, SimpleBeanPropertyFilter.serializeAllExcept("secteursEnfants")).addFilter(ModelJsonFilters.APPLICATION_FILTER,
SimpleBeanPropertyFilter.serializeAllExcept("services"));
value.setFilters(filters);
return value;
}
Place #JsonIgnore on the field or its getter, or create a custom dto
#JsonIgnore
private String encryptedPwd;
or as mentioned above by ceekay annotate it with #JsonProperty where access attribute is set to write only
#JsonProperty( value = "password", access = JsonProperty.Access.WRITE_ONLY)
private String encryptedPwd;
Can I do it dynamically?
Yes, you can use a combination of Jackson's PropertyFilter and mixins.
Explanation
Jackson has a PropertyFilter interface to implement a filter to ignore fields dynamically. The problem is that filter has to be defined on the DTO/POJO class using the #JsonFilter annotation.
To avoid adding a #JsonFilter on class we can use ObjectMapper's addMixIn method to "dynamically" add this annotation (and leave our DTO/POJO classes as is).
Code example
Here is my implementation of the idea provided above. We can call toJson() with two arguments: (1) object to be serialized and (2) lambda (Java's Predicate) to be used in PropertyFilter:
public class JsonService {
public String toJson(Object object, Predicate<PropertyWriter> filter) {
ObjectMapper mapper = new ObjectMapper();
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter("DynamicFilter", new DynamicFilter(filter));
mapper.setFilterProvider(filterProvider);
mapper.addMixIn(object.getClass(), DynamicFilterMixin.class);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new MyException(e);
}
}
private static final class DynamicFilter extends SimpleBeanPropertyFilter {
private Predicate<PropertyWriter> filter;
private DynamicFilter(Predicate<PropertyWriter> filter) {
this.filter = filter;
}
protected boolean include(BeanPropertyWriter writer) {
return include((PropertyWriter) writer);
}
protected boolean include(PropertyWriter writer) {
return filter.test(writer);
}
}
#JsonFilter("DynamicFilter")
private interface DynamicFilterMixin {
}
}
Now we can call toJson and filter fields during a serialization:
Filtering by name
new JsonService().toJson(object, w -> !w.getName().equals("fieldNameToBeIgnored"));
Filtering by annotation (on the field)
new JsonService().toJson(object, w -> w.getAnnotation(MyAnnotation.class) == null);
Unit tests
Here are the unit tests for the class above:
public class JsonServiceTest {
private JsonService jsonService = new JsonService();
#Test
public void withoutFiltering() {
MyObject object = getObject();
String json = jsonService.toJson(object, w -> true);
assertEquals("{\"myString\":\"stringValue\",\"myInteger\":10,\"myBoolean\":true}", json);
}
#Test
public void filteredByFieldName() {
MyObject object = getObject();
String json = jsonService.toJson(object, w -> !w.getName().equals("myString"));
assertEquals("{\"myInteger\":10,\"myBoolean\":true}", json);
}
#Test
public void filteredByAnnotation() {
MyObject object = getObject();
String json = jsonService.toJson(object, w -> w.getAnnotation(Deprecated.class) == null);
assertEquals("{\"myString\":\"stringValue\",\"myInteger\":10}", json);
}
private MyObject getObject() {
MyObject object = new MyObject();
object.myString = "stringValue";
object.myInteger = 10;
object.myBoolean = true;
return object;
}
private static class MyObject {
private String myString;
private int myInteger;
#Deprecated
private boolean myBoolean;
public String getMyString() {
return myString;
}
public void setMyString(String myString) {
this.myString = myString;
}
public int getMyInteger() {
return myInteger;
}
public void setMyInteger(int myInteger) {
this.myInteger = myInteger;
}
public boolean isMyBoolean() {
return myBoolean;
}
public void setMyBoolean(boolean myBoolean) {
this.myBoolean = myBoolean;
}
}
}
Would not creating a UserJsonResponse class and populating with the wanted fields be a cleaner solution?
Returning directly a JSON seems a great solution when you want to give all the model back. Otherwise it just gets messy.
In the future, for example you might want to have a JSON field that does not match any Model field and then you're in a bigger trouble.
This is a clean utility tool for the above answer :
#GetMapping(value = "/my-url")
public #ResponseBody
MappingJacksonValue getMyBean() {
List<MyBean> myBeans = Service.findAll();
MappingJacksonValue mappingValue = MappingFilterUtils.applyFilter(myBeans, MappingFilterUtils.JsonFilterMode.EXCLUDE_FIELD_MODE, "MyFilterName", "myBiggerObject.mySmallerObject.mySmallestObject");
return mappingValue;
}
//AND THE UTILITY CLASS
public class MappingFilterUtils {
public enum JsonFilterMode {
INCLUDE_FIELD_MODE, EXCLUDE_FIELD_MODE
}
public static MappingJacksonValue applyFilter(Object object, final JsonFilterMode mode, final String filterName, final String... fields) {
if (fields == null || fields.length == 0) {
throw new IllegalArgumentException("You should pass at least one field");
}
return applyFilter(object, mode, filterName, new HashSet<>(Arrays.asList(fields)));
}
public static MappingJacksonValue applyFilter(Object object, final JsonFilterMode mode, final String filterName, final Set<String> fields) {
if (fields == null || fields.isEmpty()) {
throw new IllegalArgumentException("You should pass at least one field");
}
SimpleBeanPropertyFilter filter = null;
switch (mode) {
case EXCLUDE_FIELD_MODE:
filter = SimpleBeanPropertyFilter.serializeAllExcept(fields);
break;
case INCLUDE_FIELD_MODE:
filter = SimpleBeanPropertyFilter.filterOutAllExcept(fields);
break;
}
FilterProvider filters = new SimpleFilterProvider().addFilter(filterName, filter);
MappingJacksonValue mapping = new MappingJacksonValue(object);
mapping.setFilters(filters);
return mapping;
}
}
To acheive dynamic filtering follow the link - https://iamvickyav.medium.com/spring-boot-dynamically-ignore-fields-while-converting-java-object-to-json-e8d642088f55
Add the #JsonFilter("Filter name") annotation to the model class.
Inside the controller function add the code:-
SimpleBeanPropertyFilter simpleBeanPropertyFilter =
SimpleBeanPropertyFilter.serializeAllExcept("id", "dob");
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter("Filter name", simpleBeanPropertyFilter);
List<User> userList = userService.getAllUsers();
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(userList);
mappingJacksonValue.setFilters(filterProvider);
return mappingJacksonValue;
make sure the return type is MappingJacksonValue.
Hi I have achieved dynamic filtering by using Gson library like in the below:
JsonObject jsonObj = new Gson().fromJson(mapper.writeValueAsString(sampleObject), JsonObject.class);
jsonObj.remove("someProperty");
String data = new Gson().toJson(jsonObj);
In your entity class add #JsonInclude(JsonInclude.Include.NON_NULL) annotation to resolve the problem
it will look like
#Entity
#JsonInclude(JsonInclude.Include.NON_NULL)

Categories