我正在使用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
}
谢谢您的帮助。
答案 0 :(得分:0)
You can hijack that logic in your public setter. For instance:
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
);
}
}
Then, somewhere else...
String json = "{ \"email\": \"xyz@hello.com\"}";
ObjectMapper om = new ObjectMapper();
MyPojo pojo = om.readValue(json, MyPojo.class);
System.out.println(pojo);
Output
email: xyz@hello.com, first: xyz, last: hello.com