Ipkiss
Ipkiss

Reputation: 811

mapping one json property to two different fields in java (jackson)

This is what i tried, but i get null for firstName field

@Data
@NoArgsConstractor
@AllArgsConstructor
public class User{

      @JsonProperty("name")
      private String name;
      @JsonProperty("age")
      private int age;

      private String firstName;

      public void setFirstName(String name){
        this.firstName = this.name.substring(4,10);
      }
}

lets say that i have json that i want to map to the above POJO, the problem is i want to use the @JsonProperty("name") for both name and firstName, but set the firstName slightly differently.

Upvotes: 5

Views: 5195

Answers (1)

mayha
mayha

Reputation: 603

You could use the 'JsonSetter' Annotation

@Data
@NoArgsConstractor
@AllArgsConstructor
public class User{

      private String name;
      private String firstName;

      @JsonProperty("age")
      private int age;            

      @JsonSetter("name")
      public void setNames(String name){
        this.name = name;
        this.firstName = this.name.substring(4,10);
      }
}

Upvotes: 5

Related Questions