简体   繁体   中英

Java Json Jackson saving private fields without getters and setters

I am using Jackson to save my java object (Person.class) as a json file and load from it using jackson as well.

This is what I am saving at the moment:

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;
    }

}

Even though a person's name (in this case) CANNOT be changed, nor can their year of birth, I have to have the getters and setters for Jackson to recognise the values otherwise it will give an exception:

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

How can i make my fields name and yearOfBirth (without making them PUBLIC ofcourse) final fields uneditable after initialisation.

This is my saving and loading using jackson:

saving:

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);
}

loading:

public Person load(File f) {

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

}

User @JsonProperty and it will work.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM