我试图反序列化一个YAML配置文件,它将一个特定的操作(enum)映射到参数(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杰克逊服务反序列化:
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));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());发布于 2021-10-29 18:34:37
解决办法很简单:
行动:!
https://stackoverflow.com/questions/69618623
复制相似问题