自定义Jackson的反序列化Deserializer
import lombok.Data;
@Data
public class User {
private String name;
private Integer age;
private boolean isAdult;
}
自定义Deserializer
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.ResolvableDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.File;
import java.io.IOException;
public class UserEventDeserializer extends StdDeserializer<User> implements ResolvableDeserializer {
private static final long serialVersionUID = 7923585097068641765L;
private final JsonDeserializer<?> defaultDeserializer;
public UserEventDeserializer(JsonDeserializer<?> defaultDeserializer) {
super(User.class);
this.defaultDeserializer = defaultDeserializer;
}
@Override
public User deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
User deserializedUser = (User) defaultDeserializer.deserialize(jp, ctxt);
// 业务逻辑代码,如果小于18则未成年
if (deserializedUser.getAge() < 18) {
deserializedUser.setAdult(false);
} else {
deserializedUser.setAdult(true);
}
return deserializedUser;
}
// for some reason you have to implement ResolvableDeserializer when modifying BeanDeserializer
// otherwise deserializing throws JsonMappingException??
@Override
public void resolve(DeserializationContext ctxt) throws JsonMappingException {
((ResolvableDeserializer) defaultDeserializer).resolve(ctxt);
}
public static void main(String[] args) throws IOException {
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new BeanDeserializerModifier() {
@Override
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
if (beanDesc.getBeanClass() == User.class) {
return new UserEventDeserializer(deserializer);
}
return deserializer;
}
});
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
User user = mapper.readValue("{\"name\":\"张三\",\"age\":12}", User.class);
System.out.println(user);
}
}
Loading...