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

Unable to deserialize Object Array via Jackson Yaml

我正在尝试反序列化将特定操作(枚举)映射到参数(String[])的 YAML 配置文件。为了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);

我的Jackson实现大致是这样的:

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

ObjectMapperProvider:

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

解决方法很简单:

操作:!

  • 参数:
    • 90.00 动作:!