簡體   English   中英

反序列化列表<Interface>與傑克遜

[英]Deserialize List<Interface> with 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.
@JsonDeserialize(contentAs=Bar.class)
List<IBar> bars;

為什么不直接使用TypeReference

例如...

/your/path/ Json 文件test.json

[{"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

將注釋放在IBar接口聲明而不是字段上,即:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM