杰森·杰克逊(Json Jackson)子类别/儿童领域无法识别

时间:2018-09-27 13:21:16

标签: java json performance syntax jackson

我正在使用下面的Jackson保护程序和加载程序来加载Lion类:

保存:

for (let j = 0; j < process.argv.length; j++) {  
    console.log(j + ' -> ' + (process.argv[j])); 
}

加载:

0 -> a1
1 -> a2
2 -> a3

这是我尝试加载动物类孩子的Lion时遇到的错误:

public void savePerson(File f, Animal[] cache) {
    ObjectMapper saveMapper = new ObjectMapper()
                    .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            saveMapper.setVisibilityChecker(
                saveMapper.getSerializationConfig().
                        getDefaultVisibilityChecker().
                        withFieldVisibility(JsonAutoDetect.Visibility.ANY).
                        withGetterVisibility(JsonAutoDetect.Visibility.NONE).
                        withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
            );
            ObjectWriter writer = saveMapper.writer().withDefaultPrettyPrinter();
            writer.writeValue(f, cache);
}

这是动物大师班:

public Animal[] load(File f) {

    return new ObjectMapper().readValue(f, Animal[].class); 
//i want to keep it like this instead of writing individual savers for each animal because there are hundreds of animals

}

这是Lion的子类:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "roars" (class org.game.Animal), not marked as ignorable (2 known properties: , "name", "age"])
 at [Source: data/animals/entities.json; line: 48, column: 21] (through reference chain: org.game.Animal["roars"])

我已经尝试过像在Animal类上添加子类型说明这样的事情:

public class Animal { //note is not abstract as it can be a class on its own too

    private final String name;

    private final int age;

    public Animal(@JsonProperty("name") String name, @JsonProperty("age") int age) {
        super();
        this.name = name;
        this.age = age;
    }

}

,但是在再次加载json文件时仍然会给出该错误。

我该怎么办?

注意:要保存的Animal []包括Zebra.class,Lion.class等中的常规Animal.class(不只是该数组中的一种动物)

0 个答案:

没有答案