【发布时间】:2021-08-14 18:43:04
【问题描述】:
我有一个带有 vavr 列表的 Java 对象。
@Value
@Builder(toBuilder = true)
public class Customer {
private final List<Remark> remarks;
}
当我序列化对象 objectwriter.writeValueAsString(currentDossier) 并在我看到的 JSON 输出中打印值时,
{ "remarks" : {
"empty" : true,
"lazy" : false,
"async" : false,
"traversableAgain" : true,
"sequential" : true,
"ordered" : false,
"singleValued" : false,
"distinct" : false,
"orNull" : null,
"memoized" : false
}
}
其中备注是对象内的 vavr 列表字段。
现在,如果我尝试将相同的值反序列化到对象 objectMapper.readValue(json, Customer.class) 中,则会出现错误:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `io.vavr.collection.List`
(no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (String)"{"remarks" : {
为什么尝试反序列化时序列化的 JSON 文本不起作用?
@Test
public void mapperForVavrList() throws JsonProcessingException {
Customer cus = Customer.builder().remarks(List.empty()).build();
ObjectWriter ow = new ObjectMapper()
.writer().withDefaultPrettyPrinter();
String json1 = ow.writeValueAsString(cus);
log.info(json1);
ObjectMapper objectMapper = new ObjectMapper();
Customer cus2 = objectMapper.readValue(json1, Customer.class);
log.info(cus2.toString());
}
Java 代码中是否有其他方法可以以文本格式打印 vavr 对象并将其转换回 POJO?
【问题讨论】:
-
在 Java 代码中是否有任何其他方法可以以文本格式(无论是 json、字符串等)打印 vavr 对象并使用该文本值将其更改回 POJO?我尝试了 GSON,但在将 vavr 对象转换为文本时,它似乎也无法正确打印列表值
-
Jackson 有这个功能,你需要做的就是注册 vavr-module。就是这样。
-
给你:github.com/vavr-io/vavr-jackson:
mapper.registerModule(new VavrModule());。