杰克逊解析将对象命名为同一类

时间:2016-03-21 08:53:51

标签: java json jackson

使用Jackson如何解析以下JSON:

{
    "foos" : [
        "one" : {
            "prop1" : "11",
            "prop2" : "11"
        },
        "two" : {
            "prop1" : "21",
            "prop2" : "21"
        },
        "three",
        "four"
    ]
}

进入这些课程:

public class Root {
    private Set<Foo> foos;
    // ... getter and setter
}
public class Foo {
    private String name; // this should contain the JSON name, e.g.: "one", "two", "three" 
    private String prop1;
    private String prop2;
    // ... getters and setters
}

关于JSON,我更喜欢使用命名对象而不是:

"foos" : [
    {
        "name" : "one",
        "prop1" : "11",
        "prop2" : "11"
    },
    {
        "name" : "two",
        "prop1" : "21",
        "prop2" : "21"
    },
    {
        "name" : "three"
    },
    {
        "name" : "four"
    }
]

因为大多数foos不包含其他属性,所以我不知道第一个JSON是不正确的,但它更简洁。

1 个答案:

答案 0 :(得分:1)

在这种情况下,Map符合目的

public class Root {
    private Set<Foo> foos;
    // ... getter and setter
}

public class Foo {
    Map<String, InternalFooProps> map = new HashMap<>();    
    class InternalFooProps{
        private String prop1;
        private String prop2;
        // ... getters and setters
    }
}