使用SimpleModule的Jackson MixInAnnotation不起作用

时间:2013-03-08 17:33:42

标签: java annotations jackson mixins

我正在使用SimpleModule将SerialIn注册到序列化和反序列化。我无法使它工作。课程如下所示。当我打印序列化的字符串时,我看到打印的大小和属性没有像我在mixin中指定的那样命名。正在打印{"w":5,"h":10,"size":50}。因此,串行器和反序列化配置的混合注册都不成功。我做错了什么。

MixIn类:

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;
    }
}

注册MixIn:

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);

    }
}

2 个答案:

答案 0 :(得分:3)

请改用此方法:

ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Rectangle.class, Mixin.class);

我给出了类似的回答here,提问者在评论中说模块示例(来自here)对他也不起作用。

答案 1 :(得分:3)

我没有看到您在哪里注册模块MyModule?杰克逊不会拿起它,除非你告诉它有一个模块可供使用。你有没有尝试过:

objectMapper.registerModule(new MyModule());

你的测试中的

(在你实例化ObjectMapper之后)?定义混合的模块对我来说很有用。

当然,如果您只注册了几个Mix-Ins而没有进行其他配置,那么使用addMixInAnnotations()方法会更容易。