我正在使用 SimpleModule 将 MixIn 注册为序列化和反序列化。我无法使它工作。类如下所示。当我打印序列化的字符串时,我看到打印的大小和属性没有像我在 mixin 中指定的那样命名。它正在打印{"w":5,"h":10,"size":50}
。因此,使用序列化程序和反序列化配置进行混合注册是不成功的。我究竟做错了什么。
混音类:
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
abstract class MixIn {
MixIn(@JsonProperty("width") int w, @JsonProperty("height") int h) {
}
@JsonProperty("width")
abstract int getW();
@JsonProperty("height")
abstract int getH();
@JsonIgnore
abstract int getSize();
}
矩形类:
public final class Rectangle {
final private int w, h;
public Rectangle(int w, int h) {
this.w = w;
this.h = h;
}
public int getW() {
return w;
}
public int getH() {
return h;
}
public int getSize() {
return w * h;
}
}
注册混音:
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.module.SimpleModule;
public class MyModule extends SimpleModule {
public MyModule() {
super("ModuleName", new Version(0, 0, 1, null));
}
@Override
public void setupModule(SetupContext context) {
context.setMixInAnnotations(Rectangle.class, MixIn.class);
// and other set up, if any
}
}
测试类:
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Test;
public class DeserializationTest {
@Test
public void test() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.getSerializationConfig().addMixInAnnotations(Rectangle.class, MixIn.class);
// objectMapper.getDeserializationConfig().addMixInAnnotations(Rectangle.class, MixIn.class);
String str = objectMapper.writeValueAsString(new Rectangle(5, 10));
System.out.println(str);
Rectangle r = objectMapper.readValue(str, Rectangle.class);
}
}