使用Jackson进行不对称序列化和反序列化 [英] Asymmetric serialization and deserialization using Jackson

查看:564
本文介绍了使用Jackson进行不对称序列化和反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jackson为RESTful API序列化和反序列化数据。我想要一个REST资源( / comments ),它允许POST注释以及获取注释列表。



以下是发布到 / comments 的内容的简化示例。

  {text:Text,author:Paul,email:paul@example.org} 

以下是 GET / comments 的结果应如下所示:

  [{text:Text,author:Paul,emailHash:76w0kjKP9HpsdhBjx895Sg ==}] 

由于电子邮件地址不应该对任何人可见,我决定只返回响应中电子邮件地址的MD5哈希。 / p>

我创建了一个简单的POJO类 Comment ,其中包含带有文本的getter和setter的字段 author email emailHash



现在,当我序列化结果时,得到的结果如下:

  [{ text:Text,author:Paul,email:null,emailHash:76w0kjKP9HpsdhBjx895Sg ==}] 

但我真的不喜欢将电子邮件作为 null 这里。它根本不应该被包括在内。



在该字段上使用注释 @JsonIgnore 也将忽略它关于反序列化。我是否必须使用超类注释创建两个类,例如 CreationComment ResultComment 分享公共字段还是有办法避免创建其他类?

解决方案

你不要必须创建2个类。使用Jackson,您可以在序列化和反序列化期间使用注释完全控制属性的行为,在getter中使用 @JsonIgnore 可以防止在Json响应中序列化属性在setter中使用 @JsonProperty 注释,在反序列化期间将设置该属性。代码如下所示:

  import com.fasterxml.jackson.annotation.JsonIgnore; 
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

公共类评论{

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 = new评论();
comment.setAuthor(anAuthor);
comment.setEmail(email@example.com);

try {
System.out.println(objectMapper.writeValueAsString(comment));

String json ={\author \:\anAuthor\,\email \:\another@email.com\} ;
来自于Json = objectMapper.readValue(json,Comment.class)的评论;

System.out.println(来自Json的结果:author =+ fromJson.getAuthor()+,email =+ fromJson.getEmail());

} catch(例外e){
e.printStackTrace();
}

}
}

输出在运行 main()方法来测试解决方案后:



{author :anAuthor}



Json的结果:author = anAuthor,email = another@email.com



希望有所帮助,



Jose Luis


I am using Jackson to serialize and deserialize data for a RESTful API. I'd like to have a REST resource (/comments) that allows to POST comments as well as to GET a list of comments.

Here's a (simplified) example of what gets posted to /comments.

{"text":"Text","author":"Paul","email":"paul@example.org"}

Here's what the result of GET /comments should look like:

[{"text":"Text","author":"Paul","emailHash":"76w0kjKP9HpsdhBjx895Sg=="}]

Since email addresses shouldn't be visible to anyone, I decided to return only a MD5 hash of the email addresses in the response.

I have created a simple POJO class Comment that has fields with getters and setters for text, author, email, and emailHash.

Now, when I serialize the result, what I get is the following:

[{"text":"Text","author":"Paul","email":null,"emailHash":"76w0kjKP9HpsdhBjx895Sg=="}]

But I really don't like email to be returned as null here. It rather shouldn't be included at all.

Using the annotation @JsonIgnore on that field will also ignore it on deserialization. Do I have to create two classes, say CreationComment and ResultComment with a super-class Comment that shares common fields or is there a way that avoids creating additional classes?

解决方案

You don't have to create 2 classes at all. With Jackson you have full control of the behavior of a property during serialization and deserialization using annotations, with @JsonIgnorein the getter you prevent the property from being serialized in your Json response and using @JsonProperty annotation in the setter the property will be set during deserialization. The code will look like this:

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();
        }

    }
}

The output after running the main() method to test the solution:

{"author":"anAuthor"}

Result from Json: author= anAuthor, email= another@email.com

Hope it helps,

Jose Luis

这篇关于使用Jackson进行不对称序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆