在 Spring 中编写 JSON 反序列化器或扩展它的正确方法 [英] Right way to write JSON deserializer in Spring or extend it

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

问题描述

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

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 反序列化器或扩展它的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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