我有一个Java记录,其中只有一个字段:
public record AggregateId(UUID id) {}
和一个具有AggregateId
字段的类(为了可读性,删除了其他字段)
public class Aggregate {
public final AggregateId aggregateId;
@JsonCreator
public Aggregate(
@JsonProperty("aggregateId") AggregateId aggregateId
) {
this.aggregateId = aggregateId;
}
}
上面的实现使用给定的示例对JSON进行序列化和反序列化:
ObjectMapper objectMapper = new ObjectMapper();
String content = """
{
"aggregateId": {
"id": "3f61aede-83dd-4049-a6ff-337887b6b807"
}
}
""";
Aggregate aggregate = objectMapper.readValue(content, Aggregate.class);
System.out.println(objectMapper.writeValueAsString(aggregate));
我如何更改Jackson配置以替换JSON:
{
"aggregateId": "3f61aede-83dd-4049-a6ff-337887b6b807"
}
而不放弃AggregateId
的单独类和通过字段访问,不使用getter?
我尝试了@JsonUnwrapper
注解,但这导致了抛出
Exception in thread "X" com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Invalid type definition for type `X`:
Cannot define Creator parameter as `@JsonUnwrapped`: combination not yet supported at [Source: (String)"{
"aggregateId": "3f61aede-83dd-4049-a6ff-337887b6b807"
}"
或
Exception in thread "X" com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot define Creator property "aggregateId" as `@JsonUnwrapped`:
combination not yet supported at [Source: (String)"{
"aggregateId": "3f61aede-83dd-4049-a6ff-337887b6b807"
}"
- Jackson版本:第2.13.1节 *
dependencies {
compile "com.fasterxml.jackson.core:jackson-annotations:2.13.1"
compile "com.fasterxml.jackson.core:jackson-databind:2.13.1"
}
当然,使用自定义的序列化程序/反序列化程序也是可以的,但我正在寻找一种更简单的解决方案,因为我有许多不同的类都有类似的问题。
1条答案
按热度按时间q9yhzks01#
尚不支持
@JsonUnwrapped
和@JsonCreator
的组合,因此我们可以生成如下解决方案:这里我们暂时去掉
@JsonUnwrapped
字段。我们获取名为
aggregateId
的UUID
,并创建一条**AggregateId
记录**。关于它的详细说明: