Java Jackson JsonSubType问题

时间:2015-03-19 14:19:21

标签: java json parsing jackson

我们有一些代码来解析json:

public class Main {
    private static final String TEST = "{'wrap': {'measure_score_list': [{'type':'dog dog','name':'Spike','breed':'mutt','leash_color':'red'},{'type':'cat','name':'Fluffy','favorite_toy':'spider ring'},{'type':'cat1','name':'Holy','favorite_toy':'ball'}]}}";

    public static void main(String[] args) throws Exception {
        JSONObject resultObj = JSONObject.fromObject(TEST);
        ObjectMapper mapper = new ObjectMapper().setVisibility(
                        JsonMethod.FIELD, Visibility.ANY);
        String resJson = resultObj.getString("wrap");
        Zoo zoo = mapper.readValue(resJson, Zoo.class);
    }
}
// Models
class Zoo {
    public List<Animal> animals;
}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ 
    @Type(value = Cat.class, name = "cat"),
    @Type(value = Dog.class, name = "dog dog"),
    @Type(value = Cat.class, name = "cat1")
})
abstract class Animal {
    public String name;
}

class Dog extends Animal {
    public String breed;
    public String leash_color;
}

class Cat extends Animal {
    public String favorite_toy;
}

错误日志

Could not resolve type id 'cat1' into a subtype of [simple type, class net.test.Animal]
  at [Source: java.io.StringReader@e068b6a; line: 1, column: 168] (through reference chain: net.test.Main.Zoo["animals"])

我认为杰克逊不能为多种类型提供一个类,所以它能以某种方式实现这个功能还是什么?等待你的帮助!

0 个答案:

没有答案