与杰克逊2.6.7。我正在尝试序列化/反序列化Foo
。
public class Foo {
@JsonProperty("bar")
private ValueObject<String> bar;
@JsonProperty("baz")
private ValueObject<Integer> baz;
// potentially we be stretching to have something like
// private ValueObject<OtherClass> otherObject;
// but now just the above
// getters, setters
}
public class ValueObject<T> {
private static ObjectMapper MAPPER = new ObjectMapper();
Class<T> containedClass;
JsonNode value; // This is a requirement to store it as JsonNode
String otherContext; // This is not in the original json, but something populated after the serialize/deserialization.
String anotherContext; // This is not in the original json, but something populated after the serialize/deserialization.
public ValueObject(Class<T> containedClass) {
this.containedClass = containedClass;
}
public T get() {
return MAPPER.convertValue(this.value, containedClass);
}
public void set(T value) {
if (value.getClass() != containedClass) {
throw new RuntimeException("cannot set value");
}
this.value = MAPPER.valueToTree(value);
}
// getters, setters
}
样本json
{
"bar": "BAR",
"baz": 1
}
期望的等效对象
Foo expect = new Foo();
ValueObject<String> bar = new ValueObject(String.class);
bar.set("bar");
ValueObject<Integer> baz = new ValueObejct(Integer.class);
baz.set(1);
expected.setBar(bar);
expected.setBaz(baz);
当前,我正在考虑为每种ValueObject类型实现一个CustomSerializer,例如ValueObjectStringSerializer,ValueObjectIntegerSerializer。还有另一种方法吗?