在Spring中编写JSON反序列化器或扩展它的正确方法

在Spring中编写JSON反序列化器或扩展它的正确方法

本文介绍了在Spring中编写JSON反序列化器或扩展它的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a custom JSON deserializer in Spring. I want to use default serializer for most part of fields and use a custom deserializer for few properties. Is it possible?I am trying this way because, most part of properties are values, so for these I can let Jackson use default deserializer; but few properties are references, so in the custom deserializer I have to query a database for reference name and get reference value from database.

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

I'll show some code if needed.

推荐答案

我搜索了很多,到目前为止我发现的最佳方法是:

I've searched a lot and the best way I've found so far is on this article:

要序列化的类

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。

Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.

这篇关于在Spring中编写JSON反序列化器或扩展它的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:20