2013-03-08 16 views
2

我正在使用SimpleModule向串行化和反序列化注册MixIn。我无法使它工作。这些类如下所示。当我打印序列化的字符串时,我看到打印的大小和属性未按照在mixin中指定的名称命名。这是印刷{"w":5,"h":10,"size":50}。因此,串行器和反序列化配置的混合注册失败。我究竟做错了什么。使用SimpleModule的Jackson MixInAnnotation不起作用

混合类:

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

    } 

Rectangle类:

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

    } 
} 

回答

3

我看不到你在哪里注册模块MyModule的任何地方?除非你告诉它有一个模块可以使用,否则杰克逊不会选择它。你是否尝试过做:

objectMapper.registerModule(new MyModule());

在您的测试(实例化ObjectMapper之后)?定义混合插件的模块适合我。

当然,如果您只注册几个Mix-In而不进行其他配置,则使用addMixInAnnotations()方法要容易得多。

2

使用这种方法代替:

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

我给了一个类似的答案here并在评论中指出,该模块例如(从here)他没有工作,要么提问。

+0

好的。谢谢。是的,使用ObjectMapper的作品。 – FourOfAKind 2013-03-08 18:34:34

+5

请注意,此解决方案不适用于Jackson 2.x. – Marcus 2013-10-02 18:29:07