委派模式下的Jackson JSON序列化



在我的模型中,我使用了某种委托模式。因此,我有接口A,以及实现接口的两个值对象类BC

interface A {
int getCount()
String getName()
}
class B implements A {
final int count;
final String name;
B(int count, String name) {
this.count = count;
this.name = name;
}
int getCount() {
return count;
}

String getName() {
return name;
}
}
class C implements A {
final int value;
final B delegate; 
C(B delegate, int value) {
this.delegate = delegate;
this.value = value;
}
B getDelegate() { return delegate; }
int getValue() { return value; }
int getCount() { return delegate.getCount(); }
String getName() { return delegate.getName(); }
}

然后我想将C的实例(比如new C(new B(42, "Joe"), 7)(序列化为

{
"name": "Joe",
"count": 42,
"value": 7
}

然后我需要反序列化它。我找到了一种方法来完成任务的前半部分,但我无法反序列化这样的JSON。没有自定义反序列化程序可能吗?

是的,您可以使用自定义反序列化程序来实现它,但它可能更容易修复。我认为,如果您为C类字段添加setter方法,它将正确工作。

这里有一个解决方案:

@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
class C implements A {
@JsonProperty
final int value;
@JsonUnwrapped
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
final B delegate; 
@ConstructorProperties({"name", "count", "value"});
C(String name, int count, int value) {
this.delegate = new B(count, name);
this.value = value;   
}
C(B delegate, int value) {
this.delegate = delegate;
this.value = value;
}
B getDelegate() { return delegate; }
int getValue() { return value; }
int getCount() { return delegate.getCount(); }
String getName() { return delegate.getName(); }
}

由于Jackson的限制,展开属性的特殊构造函数和访问模式有一些魔力:https://github.com/FasterXML/jackson-module-kotlin/issues/106

最新更新