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



我正在尝试反序列化一个将特定操作(enum)映射到参数(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 Service反序列化:

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

解决方法很简单:

动作:! & lt; java.util.ArrayList>

  • 参数:
    • 90.00行动:! & lt; com.walterjwhite.stackoverflow.Action>左