簡體   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