使用 ObjectMapper 序列化对象时排除 `type`

问题描述 投票:0回答:1

我正在序列化类

Foo
的实例以发送到 pubsub。我正在使用 Jackson ObjectMapper 将实例序列化为字符串,然后将其作为有效负载发送。

    @Bean(name = "gcpObjectMapper")
    public ObjectMapper gcpMenuSyncMessageObjectMapper(Jackson2ObjectMapperBuilder builder) {
        final ObjectMapper objectMapper = builder
                .createXmlMapper(false)
                .build();

        // Some other custom configuration for supporting Java 8 features
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        objectMapper.setDefaultTyping(new StdTypeResolverBuilder()
                .init(JsonTypeInfo.Id.NONE, null)
                .inclusion(JsonTypeInfo.As.EXISTING_PROPERTY)
                .typeProperty(null)
                .typeIdVisibility(false));

        return objectMapper;
    }

这个 bean 被注入到我处理消息发布的组件中:

  private ByteString convertPayload(@NotNull Foo payload) throws BusinessRuntimeException {
        try {
            String jsonString = objectMapper.writeValueAsString(payload);
            return ByteString.copyFromUtf8(jsonString);
        } catch (JsonProcessingException e) {
            log.error("Error converting payload to JSON", e);
            throw new BusinessRuntimeException(e);
        }
    }

但是,

type
键(实例的类名)仍然包含在字符串序列化的JSON中。如何配置对象映射器不包含对象的
type
信息?

java spring serialization jackson
1个回答
0
投票

要实现此目的,您需要通过添加以下内容来禁用默认输入行为:

objectMapper.deactivateDefaultTyping();

更新代码:

@Bean(name = "gcpObjectMapper")
public ObjectMapper gcpMenuSyncMessageObjectMapper(Jackson2ObjectMapperBuilder builder) {
    final ObjectMapper objectMapper = builder
            .createXmlMapper(false)
            .build();

    // Some other custom configuration for supporting Java 8 features
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

  objectMapper.deactivateDefaultTyping();

    return objectMapper;
}
© www.soinside.com 2019 - 2024. All rights reserved.