我正在尝试在 Spring 中编写自定义 JSON 反序列化器。我想对大部分字段使用默认序列化程序,并对少数属性使用自定义反序列化程序。可能吗? 我正在尝试这种方式,因为大部分属性都是值,所以对于这些我可以让 jackson 使用默认的反序列化器;但是很少有属性是引用,所以在自定义反序列化器中我必须查询数据库以获取引用名称并从数据库中获取引用值。
如果需要,我会展示一些代码。
最佳答案
我已经搜索了很多,到目前为止我发现的最好方法是在此 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());
}
}
编辑: 或者,您可以查看 this article它使用新版本的 com.fasterxml.jackson.databind.JsonDeserializer。
关于java - 在 Spring 中编写 JSON 反序列化器或对其进行扩展的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11376304/