Java Json Jackson保存没有getter和setter的私有字段

时间:2018-09-26 06:51:38

标签: java json performance jackson save

我正在使用Jackson将我的Java对象(Person.class)另存为json文件,并使用jackson对其进行加载。

这是我目前要保存的内容:

public class Person {

    private String name;

    private int yearOfBirth;

    public Person(String name, int yearOfBirth) {
       this.name = name;
       this.yearOfBirth = yearOfBirth;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getYearOfBirth() {
        return yearOfBirth
    }

    public void setYearOfBirth(int yearOfBirth) {
       this.yearOfBirth = yearOfBirth;
    }

}

即使一个人的名字(在这种情况下)不能更改,也不能改变他们的出生年份,但我必须让杰克逊(Jackson)使用吸气剂和吸气剂来识别这些值,否则它将产生例外:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "name"

初始化后,如何使我的字段名称和yearOfBirth(而不使其成为PUBLIC)最终字段不可编辑。

这是我使用杰克逊进行的保存和加载:

保存:

public void savePerson(File f, Person 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 Person load(File f) {

    return new ObjectMapper().readValue(f, Person.class);

}

1 个答案:

答案 0 :(得分:0)

用户@JsonProperty,它将正常工作。

import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {

    private final String name;

    private final int yearOfBirth;

    public Person(@JsonProperty("name") String name, @JsonProperty("yearOfBirth") int yearOfBirth) {
        this.name = name;
        this.yearOfBirth = yearOfBirth;
    }

    public String getName() {
        return name;
    }

    public int getYearOfBirth() {
        return yearOfBirth;
    }
}