使用jackson </interface>反序列化List <interface>

时间:2013-11-08 19:05:43

标签: java json serialization jackson

我想将json反序列化为类Foo:

class Foo {
   List<IBar> bars;
}

interface IBar {
   ...
}

class Bar implements IBar {
   ...
}

IBar有两个实现,但在反序列化时我总是想使用第一个实现。 (理想情况下,这应该使问题更容易,因为不需要运行时类型检查)

我确信我可以编写自定义反序列化程序,但觉得必须有更简单的东西。

我找到了这个注释,当没有列表时它可以很好地工作。

@JsonDeserialize(as=Bar.class)
IBar bar;

List<IBar> bars; // Don't know how to use the annotation here.

3 个答案:

答案 0 :(得分:25)

答案 1 :(得分:1)

为什么不使用TypeReference

例如......

test.json中的Json文件/your/path/

[{"s":"blah"},{"s":"baz"}]

test中的主要类:

public class Main {
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            List<IBar> actuallyFoos = mapper.readValue(
                    new File("/your/path/test.json"), new TypeReference<List<Foo>>() {
                    });
            for (IBar ibar : actuallyFoos) {
                System.out.println(ibar.getClass());
            }
        }
        catch (Throwable t) {
            t.printStackTrace();
        }
    }

    static interface IBar {
        public String getS();

        public void setS(String s);
    }

    static class Foo implements IBar {
        protected String s;

        public String getS() {
            return s;
        }

        public void setS(String s) {
            this.s = s;
        }
    }

    static class Bar implements IBar {
        protected String s;

        public String getS() {
            return s;
        }

        public void setS(String s) {
            this.s = s;
        }
    }
}

main方法的输出:

class test.Main$Foo
class test.Main$Foo

答案 2 :(得分:0)

将注释放在IBar接口声明而不是字段上,即:

@JsonDeserialize(as=Bar.class)
interface IBar {
   ...
}