简体   繁体   中英

Jackson library: custom mapping of a Java object in a JSON element

I have two class

public class Person {
    private long id;
    private String name;
    private Gender gender;

    // getter and setter omitted
}

and

public class Gender {
    private long id;
    private String value;

    // getter and setter omitted
}

By default the JSON mapping with Jackson library of a Person object is:

{
   id: 11,
   name: "myname",
   gender: {
      id: 2,
      value: "F"
   }
}

I'd like to known how to configure Jackson to obtain:

{
   id: 11,
   name: "myname",
   gender: "F"
}

I don't want mapping all the Gender object but only its value property.

You can use a custom serializer:

    public class GenderSerializer extends JsonSerializer<Gender> {

        public GenderSerializer() {
        }

        @Override
        public void serialize(Gender gender, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
               jgen.writeString(gender.getValue());        
        }
    }

And in your Person class:

public class Person {
    private long id;
    private String name;
    @JsonSerialize(using = GenderSerializer.class)
    private Gender gender;

}

you might wanna see this for custom mapping OR if you need a short cut then you can change getter/setter of gender like this

public String getGender(String type){
  this.getGender().getValue();
}
public void setGender(String value){
  Gender gender = new Gender();
  gender.setId(2);
  gender.setValue(value);
  this.gender = gender;
}

further you can also put condition for setting male/female on value= M/F

No need for custom serializer/deserializer if you can modify Gender class. For serialization you can use @JsonValue , for deserialization simple constructor (optionally annotated with @JsonCreator ):

public class Gender {
  @JsonCreator // optional
  public Gender(String desc) {
     // handle detection of "M" or "F"
  }

  @JsonValue
  public String asString() { // name doesn't matter
     if (...) return "M";
     return "F";
  }
}

Alternatively you could use a static factory method instead of constructor; if so, it must be annotated with @JsonCreator . And return type of method annotated with @JsonValue can be anything that Jackson knows how to serialize; here we use String, but Enum , POJO and such are fine as well.

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