简体   繁体   English

杰克逊注册自定义json序列化器

[英]Jackson register custom json serializer

This is my custom JSON Serializer and I'm trying to register it as a module. 这是我自定义的JSON Serializer,我正在尝试将其注册为模块。 Here is what I have so far. 这是我到目前为止所拥有的。

public class MaptoListSerializer extends JsonSerializer<Map<String, Car<?, ?>>> {

        @Override
        public void serialize(Map<String, Car<?, ?>> value, JsonGenerator gen, SerializerProvider serializers)throws IOException, JsonProcessingException {
             gen.writeObject(value.values());
        }
}

Here is my module class that I created ( Can't seem to add serializer ). 这是我创建的模块类( 似乎无法添加序列化程序 )。

public class CustomModule extends SimpleModule {

private static final long serialVersionUID = -9105685985325373621L;

public CustomModule() {
    super("CustomModule");
}

@Override
public void setupModule(SetupContext context) {
    SimpleSerializers serializers = new SimpleSerializers();

    //THIS DOESN'T WORK . HOW DO I ADD THE SERIALIZER?
    serializers.addSerializer(HashMap.class, new MaptoListSerializer ());

    context.addSerializers(serializers);
 }
}

Here is how Object mapper it used ( This works ) 以下是它使用的Object mapper( 这是有效的

mapper = new ObjectMapper();
mapper.registerModule(new CustomModule());

This is an issue due to using HashMap , a raw type while this case requires generics. 这是一个问题,因为使用HashMap ,一种原始类型,而这种情况需要泛型。 You can solve this by basing you custom serializer on StdSerializer as recommended in the docs. 您可以按照文档中的建议在StdSerializer创建自定义序列化程序来解决此问题。 Keep the serialize method as it is, but define serializer with a constructor like this: 保持serialize方法serialize ,但使用如下构造函数定义序列化程序:

class MaptoListSerializer extends StdSerializer<Map<String, Car<?, ?>>> {
    MaptoListSerializer(JavaType type) {
        super(type);
    }

Then to the important bit where you create an appropriate JavaType and pass it to this constructor: 然后到创建适当JavaType的重要位,并将其传递给此构造函数:

MapType type = context.getTypeFactory()
    .constructMapType(HashMap.class, String.class, Car.class);
serializers.addSerializer(new MaptoListSerializer(type));

context.addSerializers(serializers);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM