简体   繁体   中英

Jackson subclass override field

I have 2 classes

public class A {
    protected String id;
}

And

public class B extends A {
    private String bval;
}

The JSON we recieve for class B has the id with a different name, is there are way to tell jackson to use a different property name for id in classB than in classA?

Obe way to do it is to use the "any setter" feature, where Jackson is told to call a method for all "unknown" properties. You can then do the assignment yourself:

public class B extends A {

  // all unknown properties will go here
  @JsonAnySetter
  public void setUnknownProperty(String key, Object value) {
      if (key.equals("anotherNameForId")) {
          id = (String)value;
      }
  } 

I was using lombok

@Getter(onMethod = @__( @JsonProperty("id")))

and in class B

@Override
@JsonProperty("bID")
public String getId(){
    return this.id;
}

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