[英]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: 默认情况下,与Person
对象的Jackson库的JSON映射为:
{
id: 11,
name: "myname",
gender: {
id: 2,
value: "F"
}
}
I'd like to known how to configure Jackson to obtain: 我想知道如何配置Jackson以获取:
{
id: 11,
name: "myname",
gender: "F"
}
I don't want mapping all the Gender
object but only its value
property. 我不想映射所有的Gender
对象,而只映射其value
属性。
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: 在您的Person类中:
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 此外,您还可以将设置男性/女性的条件设置为值= M / F
No need for custom serializer/deserializer if you can modify Gender
class. 如果可以修改Gender
类,则无需自定义序列化器/反序列化器。 For serialization you can use @JsonValue
, for deserialization simple constructor (optionally annotated with @JsonCreator
): 对于序列化,您可以使用@JsonValue
,对反序列化简单构造函数(可选地使用@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
. 如果是这样,则必须使用@JsonCreator
进行注释。 And return type of method annotated with @JsonValue
can be anything that Jackson knows how to serialize; 用@JsonValue
注释的方法的返回类型可以是Jackson知道如何序列化的任何内容。 here we use String, but Enum
, POJO and such are fine as well. 这里我们使用String,但是Enum
,POJO等也很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.