Reputation: 822
Is there is any simple way to make Jackson fail to serialize a specific class?
Basically I want to make sure that class containing some sensitive data doesn't leak anywhere and since we log both in text and json I'm afraid it may end up getting logged as json as a part of some bigger object. (sure I could make it serialize to *****
string, but I think error makes it more clear that it's not supposed to even be used there).
My only idea right now is custom Serizalizer that just throws an exception but I was wondering if there is some simpler way to tell Jackson to stay away from that class.
Upvotes: 0
Views: 614
Reputation: 369
public class YourBlackListingSerializer extends StdSerializer<YourPojo> {
public YourBlackListingSerializer() {
this(null);
}
public YourBlackListingSerializer(Class<YourPojo> t) {
super(t);
}
@Override
public void serialize(
Item value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
throw new CustomException("This class can't be serialized");
}
}
This should work.
Then you register the serializer
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(YourPojo.class, newYourBlackListingSerializer());
mapper.registerModule(module);
However if you want to ignore just the fields then
@JsonIgnore
private String password;
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(final String password) {
this.password = password;
}
Upvotes: 1