Reputation: 2200
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.
Upvotes: 1
Views: 974
Reputation: 116472
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.
Upvotes: 0
Reputation: 26034
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;
}
Upvotes: 4
Reputation: 2922
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
Upvotes: 1