(去))在运行时以自定义方式序列化 Bean

2022-09-04 19:56:50

让我们想象一下我有以下POJO:

class Pojo {
    String s;
    Object o;
    Map<String, String> m;
}

在运行时,我希望所有属性的默认序列化/反序列化,除了一个属性。通常,我希望在序列化时将字段替换为数据库中的 ID,类似于此其他问题

例如,我想用从外部映射获取的字符串替换(例如:<=>“123”和<=>“456”):oobject1object2

  • 序列化:读取并替换(如果是,则序列化为字符串“123”)ooobject1
  • 反序列化:读取“123”,查询一些表以获取返回的原始值(即),重新创建一个带有.oobject1Pojoo = object1

我知道模块是做到这一点的一种方法,但我不确定如何在保留不需要更改的属性的自动BeanSerializer/Deserializer的同时使用它们。

有人可以举个例子(甚至是人为的)或替代方法吗?


笔记:

  • 我不能使用注释或Mixins,因为在编译时更改是未知的(即任何属性都可能以无法确定的方式更改)。
  • 另一个问题指向使用CustomSerializerFactory,它似乎可以完成这项工作。不幸的是,官方网站表明它不再是推荐的方法,应该使用模块。

编辑

为了更清楚一点,例如,我可以用Mixins执行以下操作:

ObjectMapper mapper = new ObjectMapper(MongoBsonFactory.createFactory());
mapper.addMixInAnnotations(Pojo.class, PojoMixIn.class);

ObjectReader reader = mapper.reader(Pojo.class);
DBEncoder dbEncoder = DefaultDBEncoder.FACTORY.create();
OutputBuffer buffer = new BasicOutputBuffer();
dbEncoder.writeObject(buffer, o);

与以下 Mixin:

abstract class PojoMixIn {
    @JsonIgnore Object o;
}

然后将所需的字符串添加到 JSON 内容中。但是我需要在编译时知道这是需要替换的字段,而我没有。o


答案 1

我认为并且是你需要的。通过这些批注,您可以控制特定字段的序列化/反序列化。这个问题展示了将它们组合成一个注释的优雅方法。@JsonSerialize@JsonDeserialize

UPD。对于此复杂方案,您可以查看类。我们的想法是使用特定字段的自定义逻辑修改常规,并让基本实现来执行其他操作。稍后将发布一个示例。BeanSerializerModifier/BeanDeserializerModifierBeanSerializer/BeanDeserializer

UPD2.正如我所看到的,其中一种方法可能是使用方法并分配自己的序列化程序。changeProperties

UPD3.使用自定义序列化程序的工作示例进行了更新。反序列化也可以用类似的方式完成。

UPD4.更新了具有完全自定义序列化/反序列化的示例。(我用了jakson-mapper-asl-1.9.8)

  public class TestBeanSerializationModifiers {

    static final String PropertyName = "customProperty";
    static final String CustomValue = "customValue";
    static final String BaseValue = "baseValue";

    // Custom serialization

    static class CustomSerializer extends JsonSerializer<Object> {
        @Override
        public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
            String customValue = CustomValue; // someService.getCustomValue(value);
            jgen.writeString(customValue);
        }
    }

    static class MyBeanSerializerModifier extends BeanSerializerModifier {
        @Override
        public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BasicBeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
            for (int i = 0; i < beanProperties.size(); i++) {
                BeanPropertyWriter beanPropertyWriter = beanProperties.get(i);
                if (PropertyName.equals(beanPropertyWriter.getName())) {
                    beanProperties.set(i, beanPropertyWriter.withSerializer(new CustomSerializer()));
                }
            }
            return beanProperties;
        }
    }

    // Custom deserialization

    static class CustomDeserializer extends JsonDeserializer<Object> {
        @Override
        public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            // serialized value, 'customValue'
            String serializedValue = jp.getText();
            String baseValue = BaseValue; // someService.restoreOldValue(serializedValue);
            return baseValue;
        }
    }

    static class MyBeanDeserializerModifier extends BeanDeserializerModifier {
        @Override
        public BeanDeserializerBuilder updateBuilder(DeserializationConfig config, BasicBeanDescription beanDesc, BeanDeserializerBuilder builder) {
            Iterator<SettableBeanProperty> beanPropertyIterator = builder.getProperties();
            while (beanPropertyIterator.hasNext()) {
                SettableBeanProperty settableBeanProperty = beanPropertyIterator.next();
                if (PropertyName.equals(settableBeanProperty.getName())) {
                    SettableBeanProperty newSettableBeanProperty = settableBeanProperty.withValueDeserializer(new CustomDeserializer());
                    builder.addOrReplaceProperty(newSettableBeanProperty, true);
                    break;
                }
            }
            return builder;
        }
    }

    static class Model {

        private String customProperty = BaseValue;
        private String[] someArray = new String[]{"one", "two"};

        public String getCustomProperty() {
            return customProperty;
        }

        public void setCustomProperty(String customProperty) {
            this.customProperty = customProperty;
        }

        public String[] getSomeArray() {
            return someArray;
        }

        public void setSomeArray(String[] someArray) {
            this.someArray = someArray;
        }
    }

    public static void main(String[] args) {
        SerializerFactory serializerFactory = BeanSerializerFactory
                .instance
                .withSerializerModifier(new MyBeanSerializerModifier());

        DeserializerFactory deserializerFactory = BeanDeserializerFactory
                .instance
                .withDeserializerModifier(new MyBeanDeserializerModifier());

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializerFactory(serializerFactory);
        objectMapper.setDeserializerProvider(new StdDeserializerProvider(deserializerFactory));

        try {
            final String fileName = "test-serialization.json";
            // Store, "customValue" -> json
            objectMapper.writeValue(new File(fileName), new Model());
            // Restore, "baseValue" -> model
            Model model = objectMapper.readValue(new File(fileName), Model.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

答案 2