【问题标题】:Spring Boot custom serializer for Collection classCollection 类的 Spring Boot 自定义序列化程序
【发布时间】:2019-03-19 12:04:22
【问题描述】:

我试图为我的对象的一个​​属性实现一个自定义序列化程序,以便在我从 REST 控制器返回它时获得不同的 JSON 结构。

我的限制是我无法更改 REST 控制器或模型类的接口(因此我无法添加额外的注释等,这可能会使这更容易)。我唯一能想到的,使它呈现与模型中描述的不同的是自定义序列化程序,如果有更好的方法,请不要犹豫,告诉我在约束范围内的不同方法。

我的模型看起来像这样:

public class WrapperModel {

  // a lot of autogenerated fields

  List<Property> properties;

  // getters/setters
}

public class Property {

  private String name;

  private String value;

  // getters / setters

}

所以当它被渲染时是这样的:

{   ....   
    "properties": [
      {"key1": "value1"}, {"key2": "value2"},...   
    ] 
}

我想要的是这样的:

{   ....   
    "properties": {
      "key1": "value1",
      "key2": "value2",
      ...  
    }
}

这个序列化器很简单:

public class PropertyListJSONSerializer extends StdSerializer<List<Property>> {

//....

@Override
public void serialize(List<Property> value, JsonGenerator gen,   SerializerProvider provider) throws IOException {
    gen.writeStartObject();
    for(Property p: value){
        gen.writeStringField(p.getName(), p.getValue());
    }
    gen.writeEndObject();
}

}

现在,当我尝试在 @Configuration 文件中注册此序列化程序时:

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    SimpleModule module = new SimpleModule();
    module.addSerializer(List<Property>.class, new PropertyListJSONSerializer());
    mapper.registerModule(module);

    return mapper;
}

这不起作用,因为List&lt;Property&gt;.class 不能用于addSerializer,因为它是一个模板类。有没有其他方法可以添加这个序列化程序或类似的东西?

我不想为WrapperModel 添加自定义序列化程序,因为此类是自动生成的,并且可以添加和删除字段。这应该可以在不修改应用程序代码的情况下实现(如果我有自定义序列化程序,您还需要从序列化程序中添加/删除字段(?))。或者有没有办法只为类使用标准序列化程序并手动处理这个List&lt;&gt; 字段。

模型类是由 Spring Boot openapi 代码生成器生成的,因此我可以在模型字段之上放置一组非常有限的 JSON 注释(如果有注释方式,请不要犹豫,尽可能发布如果支持该特定注释,请检查 openapi 源代码)。但如果可能的话,我宁愿为List&lt;Property&gt; 使用自定义序列化程序,或者为WrapperModel 编写一个对所有内容都使用StdSerializer 的序列化程序,并且只自己处理List 属性。

【问题讨论】:

    标签: java spring-boot jackson


    【解决方案1】:

    混入

    在这种情况下,我们需要使用MixIn 功能。创建如下界面:

    interface WrapperModelMixIn {
    
        @JsonSerialize(using = PropertyListJSONSerializer.class)
        List<Property> getProperties();
    }
    

    然后像下面这样注册:

    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixInAnnotations(WrapperModel.class, WrapperModelMixIn.class);
    

    旧提案

    您需要使用Jackson 允许为泛型类型注册序列化程序的类型。更改后的序列化程序可能如下所示:

    class PropertyListJSONSerializer extends StdSerializer<List<Property>> {
    
        public PropertyListJSONSerializer(JavaType type) {
            super(type);
        }
    
        @Override
        public void serialize(List<Property> value, JsonGenerator gen, SerializerProvider provider)
            throws IOException {
            gen.writeStartObject();
            for (Property p : value) {
                gen.writeStringField(p.getName(), p.getValue());
            }
            gen.writeEndObject();
        }
    }
    

    您可以按如下方式注册:

    ObjectMapper mapper = new ObjectMapper();
    
    CollectionType propertiesListType = mapper.getTypeFactory().constructCollectionType(List.class, Property.class);
    SimpleModule module = new SimpleModule();
    module.addSerializer(new PropertyListJSONSerializer(propertiesListType));
    mapper.registerModule(module);
    

    【讨论】:

    • 嘿,谢谢,这看起来正是我正在寻找的解决方案。我尝试了这个,并在序列化方法中放置了一个断点,因为我没有输出。现在,每个 List 都会调用序列化程序,而不仅仅是 List
    • @Tom,你是对的,我假设你只有一个列表。您需要使用MixIn 功能。看看更新的版本。
    • 哇,我不知道MixIn,.. 这真的很强大,可能会解决很多我还不知道的问题xD。再次感谢,留给我的唯一问题是,PropertyListJSONSerializer 现在没有无参数构造函数。我需要在序列化程序上使用类型/类调用 ​​super 并且不知道如何在构造函数中使用 CollectionType.construct。
    • @Tom,是的,MixIn 是一个很棒的功能。您可以使用相关类中的静态方法构造类似类型的集合:CollectionType.construct(List.class, SimpleType.construct(Property.class)) 应该可以工作。将其传递给super构造函数
    • 谢谢,现在完美运行!感觉今天真的学到了有用的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 2019-01-05
    • 2016-12-31
    • 2017-11-18
    • 1970-01-01
    • 2019-04-11
    • 2017-08-10
    相关资源
    最近更新 更多