It seems you can't mix @JsonIgnore and @JsonView. I want to hide a field by default, but show it in some cases.
Basically I've got this setup :-
class Parent extends Model {
public Long id;
public Child child;
}
class Child extends Model {
public Long id;
@JsonView(Full.class)
public String secret;
public static class Full {};
}
And want to use play.libs.Json.toJson(parent)
to render WITHOUT child.secret, and
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter w = objectMapper.writerWithView(Child.Full.class);
return ok(w.writeValueAsString(child));
to render WITH child.secret. Is there any way to do this. i.e. is there any way to set a field to ignore by default, but get included with a particular JsonView?
Currently BOTH calls include the secret.
Thanks!
Once you have an object mapper, you can effectively use it in the same way as you are currently using play.libs.Json.toJson(parent)
, and get exactly what you want.
So whenever you were previously using play.libs.Json.toJson(parent)
, just use new ObjectMapper().writeValueAsString()
and you won't get your secret.
You may try JsonFilter in your child class you need to add this annotation @JsonFilter("myFilter")
@JsonFilter("myFilter") // myFilter is the name of the filter, you can give your own.
class Child extends Model {
public Long id;
public String secret;
}
ObjectMapper mapper = new ObjectMapper();
/* Following will add filter to serialize all fields except the specified fieldname and use the same filter name which used in annotation.
If you want to ignore multiple fields then you can pass Set<String> */
FilterProvider filterProvider = new SimpleFilterProvider().addFilter("myFilter",SimpleBeanPropertyFilter.serializeAllExcept("secret"));
mapper.setFilters(filterProvider);
try {
String json = mapper.writeValueAsString(child);
} catch (JsonProcessingException e) {
Logger.error("JsonProcessingException ::: ",e);
}
If you dont want to ignore any field then, just pass empty string `SimpleBeanPropertyFilter.serializeAllExcept("")`