[英]JSON deserialiser to set custom properties in POJO
我正在使用Jackson在Java POJO上進行json映射。 我想要的是通過拆分JSON值從POJO中設置兩個屬性。
{
"email": "xyz@hello.com",
}
POJO是
public class TestPojo {
@JsonProperty("email")
private String emailAddress;
/*is there any annotation available that I can split the email
address with a delimiter which is '@' to first and second
properties*/
private String first; //gives value xyz
private String second;//gives value hello.com
}
感謝您的幫助。
您可以在公共設置器中劫持該邏輯。 例如:
class MyPojo {
// no need for this annotation here actually, covered by setter
// at least for deserialization
@JsonProperty
String email;
String first;
String last;
@JsonProperty("email")
public void setEmail(String email) {
this.email = email;
String[] split = email.split("@");
// TODO check length etc.
this.first = split[0];
this.last = split[1];
}
// just for testing
@Override
public String toString() {
return String.format(
"email: %s, first: %s, last: %s%n", email, first, last
);
}
}
然后,在其他地方
String json = "{ \"email\": \"xyz@hello.com\"}";
ObjectMapper om = new ObjectMapper();
MyPojo pojo = om.readValue(json, MyPojo.class);
System.out.println(pojo);
產量
email: xyz@hello.com, first: xyz, last: hello.com
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.