Skip to content
Advertisement

How to Use @JsonProperty With Lombok?

Suppose we have a json response that we want to map it to our java class.

{
    "access_token": "abcdefg..."
}

I had a data class that mapped access_token field in the json to accessToken field in the code. I used to use @JsonProperty annotation on getters and setters.

private String accessToken;

@JsonProperty("accessToken")
public String getAccessToken() {
    return accessToken;
}

@JsonProperty("access_token")
public void setAccessToken(String accessToken) {
    this.accessToken = accessToken;
}

Then I decided to use Lombok annotations @Getter and @Setter. Since I do not have a getter and setter in my code, how can I map access_token field in the json to accessToken field in the code with Lombok annotations?

My code is like this right now and as you can expect, it cannot map the fields.

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Token {
    private String accessToken;
}

I do not want to name my variable to access_token because I also return access token as a json response and I want it to appear as accessToken in my json response.

Thank you.

Advertisement

Answer

Found a way to do it.

@NoArgsConstructor
@AllArgsConstructor
public class Token {
    @Setter(onMethod = @__(@JsonSetter(value = "access_token"))) 
    @Getter(onMethod = @__(@JsonGetter(value = "accessToken"))) 
    private String accessToken;
}

Another solution is to use @JsonAlias annotation.

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Token {
    @JsonAlias("access_token"))) 
    private String accessToken;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement