Decode base64 encoded JSON to POJO with jackson and spring-boot

后端 未结 1 1621
南旧
南旧 2021-01-15 08:49

I have a request coming like this

{
    \"varA\"  : \"A\",
    \"varB\" : \"TCFNhbiBKb3NlMRgwFgYDVQQK\"
}

where key varB is a

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 09:33

    I've done some experiments and here is a simple Jackson Deserializer which should work for you.

    Deserializer implements the ContextualDeserializer interface to get access to actual bean property (for example varB). It's necessary for detecting correct result type, because deserializer itself can be attached to a field of any type.

    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 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.Decoder decoder = Base64.getDecoder();
    
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                byte[] decodedValue = decoder.decode(value);
    
                return objectMapper.readValue(decodedValue, 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 encoded JSON", fieldName),
                    value,
                    wrapperClass
                );
            }
        }
    }
    
    
    

    Here is an example of mapped class.

    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;
        }
    }
    

    0 讨论(0)
    提交回复
    热议问题