对json的一部分使用不同的对象映射器

时间:2019-04-28 15:42:49

标签: java json jackson objectmapper jackson-databind

对于我们的服务输入,我们使用带有某些配置的对象映射器将其序列化。我们在client-lib中为客户端提供相同的对象映射器配置,并在末尾使用相同的对象反序列化输入。

现在,我们将另一个对象添加到我们的输入中,该对象归一个普通团队所有,并具有自己的对象映射器配置以正确序列化它。

class MyAPIRequest {
    MyOtherOwnedClass1 obj1;
    MyOtherOwnedClass2 obj2;

    //New Shared class which is being added as part of input now: 
    CommonlyOwnedClass newObj;

}


class MyAPIRequestObjectMapperFactory() {
   static ObjectMapper newInstance(IonSystem ionSystem) {
        final ObjectMapper  objectMapper = new ObjectMapper();                 
        objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);

        return objectMapper;
    }
}

class CommonlyOwnedClassObjectMapperFactory() {
   static ObjectMapper newInstance(IonSystem ionSystem) {
        final ObjectMapper  objectMapper = new ObjectMapper();                 
        objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY);
        objectMapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.ANY);

        return objectMapper;
    }
}

如何更新我的ObjectMapper以对newObj使用不同的ObjectMapper(由CommonlyOwnedClassObjectMapperFactory提供),并继续对MyAPIRequestObjectMapperFactory中的其余对象使用现有的对象映射器(在MyAPIRequest中) ?

编辑: 我正在使用Jackson-2.8,但如果需要可以升级到2.9

1 个答案:

答案 0 :(得分:0)

setVisibility方法由受保护的配置变量(在2.8中为_serializationConfig&_deserializationConfig和在2.9中为_configOverrides)控制。 setVisibility方法已重载,这需要可见性检查器覆盖内部配置变量。您可以通过从外部映射器获取可见性检查器来使用重载版本为映射器设置配置。

ObjectMapper yourObjectMapper = MyAPIRequestObjectMapperFactory.newInstance();
    ObjectMapper externalObjectMapper = CommonlyOwnedClassObjectMapperFactory.newInstance();
    yourObjectMapper.setVisibility(externalObjectMapper.getVisibilityChecker());
    //then set your visibility