对于我们的服务输入,我们使用具有某些配置的对象映射器来序列化它。我们在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以使用不同的ObjectMapper(由CommonlyOwnedClassObjectMapperFactory
提供)用于newObj并继续使用现有的对象映射器(在MyAPIRequestObjectMapperFactory
中)用于MyAPIRequest
中的其余对象?
编辑:我使用的是Jackson-2.8,但如果需要可以升级到2.9
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