0

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

}
Arturo Seijas
  • 194
  • 1
  • 8
kay
  • 451
  • 1
  • 3
  • 13

1 Answers1

1

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;
    }
}
ProgrammerBoy
  • 876
  • 6
  • 19