ShadyBears
ShadyBears

Reputation: 4175

Is there an alternative to deserializing using setters and @JsonProperty for Spring

Just using two very basic examples.. is there an alternative to deserializing JSON to a POJO where I don't need to create setters and where I don't need to declare @JsonProperty on each field?

@JsonProperty seems tedious and repetitive
Setters seems to weaken encapsulation.

Using setters:

public class Person{
    private int age;
    private String name;

    public int getAge(){
        return age;
    }

    public void setAge(int age){
        this.age = age;
    }

    public String getName(){
        return name;
    }

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

Using @JsonProperty:

public class Person{
    @JsonProperty private int age;
    @JsonProperty private String name;

    public int getAge(){
        return age;
    }

    public String getName(){
        return name;
    }
}

Upvotes: 0

Views: 1796

Answers (3)

Ken Chan
Ken Chan

Reputation: 90427

Jackson has the auto-detection feature which by default will only deserialise all public fields and all setters. That 's why if all of the fields are private , nothing will be deserialised if there are no setters.

You can use @JsonAutoDetect to configure this auto-detection feature such that it will deserialise even the fields are private. So in this way , you don't not need to add any setters anymore.

To configure per object :

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class Person{
    private int age;
    private String name;
}

To configure globally such that you do not need to configure for each object:

ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

Upvotes: 2

Avi
Avi

Reputation: 1528

For Getter/Setter try using Lombok, could refer this https://www.baeldung.com/intro-to-project-lombok.

Main goal of Lombok is to reduce boiler plate code and it is pretty much useful.

And about @JsonProperty, if you don't mark the attribute with the annotation the package will not know which should it serializer or deserialize.So no other go

Upvotes: 0

Álex Fog
Álex Fog

Reputation: 84

An alternative is creating a Builder, in which the only annotations that Jackson needs are @JsonDeserialize and @JsonPOJOBuilder, e.g:

@JsonDeserialize(builder = Person.Builder.class)
public class Person {
  ...
  @JsonPOJOBuilder(buildMethodName = "build", withPrefix = "")
  public static class Builder {
    ...
    public Builder age(final int age) {
      this.age = age;
      return this;
    }
    ...
  }
}

I believe it's as tedious as annotating each field with @JsonProperty, but in terms of immutability it's better than setters.

Upvotes: 0

Related Questions