Java中如何使用@JsonDeserialize注解实现自定义反序列化呢?
下文笔者讲述@JsonDeserialize注解应用到JSON序列化的示例分享,如下所示
@JsonDeserialize注解的功能简介
@JsonDeserialize注解: 将JSON反序列化为Java对象时声明自定义反序列化器 可通过使用泛型类型User 继承 StdDeserializer 类来实现自定义反序列化器 此时需要重写StdDeserializer类的deserialize()方法
@JsonDeserialize注解的语法
@Target(value={ANNOTATION_TYPE,METHOD,FIELD,TYPE,PARAMETER}) @Retention(value=Runtime) public @interface JsonDeserialize
@JsonDeserialize注解的示例
import java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.*; import com.fasterxml.jackson.databind.deser.std.*; public class JsonDeSerializeAnnotationTest { public static void main (String[] args) throws JsonProcessingException, IOException { User user = new User(888, "maomao"); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(user); user = mapper.readValue(jsonString, User.class); System.out.println(user); } } // CustomDeserializer 类 class CustomDeserializer extends StdDeserializer<User> { public CustomDeserializer(Class<User> t) { super(t); } public CustomDeserializer() { this(User.class); } @Override public User deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { int id = 0; String name = null; JsonToken currentToken = null; while((currentToken = jp.nextValue()) != null) { switch(currentToken) { case VALUE_NUMBER_INT: if(jp.getCurrentName().equals("id")) { id = jp.getIntValue(); } break; case VALUE_STRING: switch(jp.getCurrentName()) { case "name": name = jp.getText(); break; default: break; } break; default: break; } } return new User(id, name); } } // User 类 @JsonDeserialize(using=CustomDeserializer.class) class User { private int id; private String name; public User(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } @Override public String toString() { StringBuilder sb = new StringBuilder("ID: ").append(this.id).append("\nName: ").append(this.name); return sb.toString(); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。