4

这是我的自定义 JSON 序列化器,我正在尝试将其注册为模块。这是我到目前为止所拥有的。

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());
        }
}

这是我创建的模块类(似乎无法添加序列化程序)。

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);
 }
}

这是它使用的对象映射器的方式(这有效

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

1 回答 1

3

这是由于使用HashMap原始类型而导致的问题,而这种情况需要泛型。您可以按照文档中的建议,通过基于StdSerializer的自定义序列化程序来解决此问题。保持serialize方法不变,但使用如下构造函数定义序列化程序:

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

然后到您创建适当JavaType并将其传递给此构造函数的重要位:

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

context.addSerializers(serializers);
于 2017-11-23T11:26:33.333 回答