小编典典

在Spring中编写JSON解串器或对其进行扩展的正确方法

json

我正在尝试在Spring中编写自定义JSON反序列化器。我想对大部分字段使用默认的序列化程序,而对少数属性使用自定义的反序列化程序。可能吗?我正在尝试这种方式,因为大多数属性都是值,因此对于这些,我可以让Jackson使用默认的反序列化器;但是属性很少是引用,因此在自定义反序列化器中,我必须查询数据库以获取引用名称并从数据库中获取引用值。

如果需要,我将显示一些代码。


阅读 252

收藏
2020-07-27

共1个答案

小编典典

我进行了很多搜索,到目前为止,找到最好的方法是在这篇文章上

类进行序列化

package net.sghill.example;

import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private ObjectId id;
    private String   username;
    private String   password;

    public User(ObjectId id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public ObjectId getId()       { return id; }
    public String   getUsername() { return username; }
    public String   getPassword() { return password; }
}

反序列化器类

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

编辑:或者你可以看看这篇文章,它使用com.fasterxml.jackson.databind.JsonDeserializer的新版本。

2020-07-27