1

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.

3 Answers 3

4

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; } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thank you! you brought me in the right direction. I found this link: baeldung.com/jackson-custom-serialization that is what I'm looking for.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.