繁体   English   中英

无法通过 Jackson Yaml 反序列化对象数组

[英]Unable to deserialize Object Array via Jackson Yaml

我正在尝试反序列化一个 YAML 配置文件,该文件将特定操作(枚举)映射到参数(String[])。 为了有一个 YAML 的起点,我首先用 Java 构建了对象结构,然后将其序列化。

读回该输出并反序列化它也会导致下面的异常,这是出乎意料的,因为它直接来自马口。

我的Java结构:

@NoArgsConstructor
@AllArgsConstructor
@ToString(doNotUseGetters = true)
@Data
public class Session {
  @EqualsAndHashCode.Exclude protected List<ActionInstance> actions;
}

@NoArgsConstructor
@AllArgsConstructor
@ToString(doNotUseGetters = true)
@Data
public class ActionInstance {
  protected Action action;
  protected String[] arguments;
}

public enum Action {
  Left,
  Right,
  Up,
  Down;
}

YAML(这直接取自 Jackson 的序列化输出,读回会导致以下异常):

actions: !<java.util.ImmutableCollections$List12>
- !<java.util.ImmutableCollections$List12>
  arguments:
  - 90.00
  action: Left

用于反序列化的 Jackson 服务:

objectMapper.readValue(inputStream, Session.class)

例外:

com.fasterxml.jackson.databind.exc.MismatchedInputException
Unexpected token (VALUE_STRING), expected START_ARRAY: need JSON Array to contain As.WRAPPER_ARRAY type information for class Action

编辑#1:

final Session export = new Session();
        export.setActions(
            List.of(
                new ActionInstance(Action.Left, new String[] {"90.00"})));
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        serializationService.serialize(export, baos);

我的杰克逊实现大致是这样的:

outputStream.write(objectMapper.writeValueAsBytes(data));

对象映射器提供者:

public class ObjectMapperProvider implements Provider<ObjectMapper> {
  protected final ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
  protected final JavaTimeModule javaTimeModule = new JavaTimeModule();

  @Inject
  public ObjectMapperProvider() {
    // Hack time module to allow 'Z' at the end of string (i.e. javascript json's)
    javaTimeModule.addDeserializer(
        LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));
    objectMapper.registerModule(javaTimeModule);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator());

解决方法很简单:

动作: !<java.util.ArrayList>

  • 论据:
    • 90.00 动作:!<com.walterjwhite.stackoverflow.Action> 左

暂无
暂无

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

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