我已经做了一些实验,这是一个简单的Jackson Deserializer,应该可以为您工作。
Deserializer实现ContextualDeserializer接口以访问实际的bean属性(例如
varB)。这是检测正确结果类型的必要条件,因为解串器本身可以附加到任何类型的字段。
import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.*;import com.fasterxml.jackson.databind.deser.ContextualDeserializer;import com.fasterxml.jackson.databind.exc.InvalidFormatException;import java.io.IOException;import java.util.base64;public class base64Deserializer extends JsonDeserializer<Object> implements ContextualDeserializer { private Class<?> resultClass; @Override public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) throws JsonMappingException { this.resultClass = property.getType().getRawClass(); return this; } @Override public Object deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { String value = parser.getValueAsString(); base64.Deprer deprer = base64.getDeprer(); try { ObjectMapper objectMapper = new ObjectMapper(); byte[] depredValue = deprer.depre(value); return objectMapper.readValue(depredValue, this.resultClass); } catch (IllegalArgumentException | JsonParseException e) { String fieldName = parser.getParsingContext().getCurrentName(); Class<?> wrapperClass = parser.getParsingContext().getCurrentValue().getClass(); throw new InvalidFormatException( parser, String.format("Value for '%s' is not a base64 enpred JSON", fieldName), value, wrapperClass ); } }}这是一个映射类的例子。
public class MyRequest { private String varA; @JsonDeserialize(using = base64Deserializer.class) private B varB; public String getVarA() { return varA; } public void setVarA(String varA) { this.varA = varA; } public B getVarB() { return varB; } public void setVarB(B varB) { this.varB = varB; }}


