简体   繁体   English

使杰克逊在类的序列化尝试中失败

[英]Make jackson fail on serialization attempt of a class

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.基本上我想确保包含一些敏感数据的类不会泄漏到任何地方,因为我们同时登录 text 和 json 我担心它最终可能会被记录为 json 作为某个更大对象的一部分。 (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.我现在唯一的想法是自定义 Serizalizer,它只会引发异常,但我想知道是否有一些更简单的方法可以告诉 Jackson 远离该类。

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;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM