pvo*_*orb 4 java serialization json jackson
我正在使用Jackson为RESTful API序列化和反序列化数据.我想要一个REST资源(/comments),它允许POST注释以及获取注释列表.
这是一个(简化的)发布内容的示例/comments.
{"text":"Text","author":"Paul","email":"paul@example.org"}
Run Code Online (Sandbox Code Playgroud)
这是结果GET /comments应该是什么样的:
[{"text":"Text","author":"Paul","emailHash":"76w0kjKP9HpsdhBjx895Sg=="}]
Run Code Online (Sandbox Code Playgroud)
由于任何人都不应该看到电子邮件地址,因此我决定只返回响应中电子邮件地址的MD5哈希值.
我创建了一个简单的POJO类Comment是具有getter和setter方法领域text,author,email,和emailHash.
现在,当我序列化结果时,我得到的是以下内容:
[{"text":"Text","author":"Paul","email":null,"emailHash":"76w0kjKP9HpsdhBjx895Sg=="}]
Run Code Online (Sandbox Code Playgroud)
但我真的不喜欢email像null这里一样被退回.它根本不应该被包括在内.
@JsonIgnore在该字段上使用注释也将在反序列化时忽略它.我是否必须创建两个类,比如说CreationComment和ResultComment一个Comment共享公共字段的超类或者有没有办法避免创建其他类?
您根本不必创建2个类.使用Jackson,您可以在序列化和反序列化期间使用注释完全控制属性的行为,@JsonIgnore在getter中,您可以防止在Json响应中序列化属性,并@JsonProperty在setter中使用注释,在反序列化期间将设置属性.代码如下所示:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Comment {
private String author;
private String email;
@JsonIgnore
public String getEmail() {
return email;
}
@JsonProperty
public void setEmail(String email) {
this.email = email;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
Comment comment = new Comment();
comment.setAuthor("anAuthor");
comment.setEmail("email@example.com");
try {
System.out.println(objectMapper.writeValueAsString(comment));
String json = "{\"author\":\"anAuthor\",\"email\":\"another@email.com\"}";
Comment fromJson = objectMapper.readValue(json, Comment.class);
System.out.println("Result from Json: author= " + fromJson.getAuthor() + ", email= " + fromJson.getEmail());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
运行main()方法测试解决方案后的输出:
{"author":"anAuthor"}
Result from Json: author= anAuthor, email= another@email.com
希望能帮助到你,
何塞路易斯