【问题标题】:Jackson Serializer called on wrong typesJackson Serializer 调用了错误的类型
【发布时间】:2018-05-08 17:39:18
【问题描述】:

我正在与 Jackson 合作,我编写了以下自定义序列化程序:

public class FooSerializer extends StdSerializer<List<Foo>> {

  public FooSerializer() {
    this(null);
  }

  public FooSerializer(Class<List<Foo>> t) {
    super(t);
  }

  public void serialize(List<Foo> foos, JsonGenerator gen, SerializerProvider provider) throws IOException {
    gen.writeStartArray(foos.size());
    for(Foo foo : foos){
        gen.writeString(foo.getName());
    }
    gen.writeEndArray();
  }
}

我已经在ObjectMapper注册了如下:

SimpleModule fooModule = new SimpleModule("Foo Module");
fooModule.addSerializer(new FooSerializer((Class<List<Foo>>)(Object)List.class));
objectMapper.registerModule(fooModule);

我希望它获取一个持有ListFoos 的对象并像返回它一样

{
  ...
  "foos":["name1", "name2"]
  ...
}

这工作正常,但是,当我传递 SomeObjectHoldingFoosList 时,每个都持有 FooList,ObjectMapper 尝试将 FooSerializer 应用到这个 List 已经,导致Foo cannot be cast to SomeObjectHoldingFoos 异常。

我怀疑 FooSerializerhandledType 不知何故被设置为 List 而不是 List&lt;Foo&gt; 但我不知道如何解决这个问题,因为似乎没有参数化的类输入。

我能做什么?

【问题讨论】:

  • 刚刚通过代码我想知道 List.class 是否可以在 addSerializer 部分中替换为 List.class

标签: json list serialization jackson objectmapper


【解决方案1】:

使用JavaType 而不是Class

class FooSerializer extends StdSerializer<List<Foo>> {

    FooSerializer(JavaType javaType) {
        super(javaType);
    }

    ....
}

并像下面这样注册:

SimpleModule fooModule = new SimpleModule("Foo Module");
CollectionLikeType type = mapper.getTypeFactory().constructCollectionLikeType(ArrayList.class, Foo.class);
fooModule.addSerializer(new FooSerializer(type));

【讨论】:

  • 我找到了另一个使用 StdConverter 的解决方案,但这也可以,谢谢。
【解决方案2】:

我意识到我只需要Converter 而不是Serializer,我已经实现了以下内容:

public class FooConverter extends StdConverter<Foo, String> {

  @Override
  public String convert(Foo value) {
    return value.getName();
  }

  public static SimpleModule getSimpleModule(){
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(Foo.class, new StdDelegatingSerializer(new FooConverter()));
    return simpleModule;
  }
}

我注册如下:

SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(TAGWrapper.class, new StdDelegatingSerializer(new TagWrapperConverter()));
objectMapper.registerModule()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2015-09-25
    • 2017-05-29
    • 1970-01-01
    相关资源
    最近更新 更多