Can Jackson be configured to trim leading/trailing whitespace from all string properties?

前端 未结 6 1975
别跟我提以往
别跟我提以往 2020-12-08 06:46

Example JSON (note that the string has trailing spaces):

{ \"aNumber\": 0, \"aString\": \"string   \" }

Ideally, the deserialised instance

6条回答
  •  执笔经年
    2020-12-08 06:53

    For Spring Boot, we just have to create a custom deserializer as documented in the manual.

    The following is my Groovy code but feel free to adapt it to work in Java.

    import com.fasterxml.jackson.core.JsonParser
    import com.fasterxml.jackson.databind.DeserializationContext
    import com.fasterxml.jackson.databind.JsonDeserializer
    import org.springframework.boot.jackson.JsonComponent
    
    import static com.fasterxml.jackson.core.JsonToken.VALUE_STRING
    
    @JsonComponent
    class TrimmingJsonDeserializer extends JsonDeserializer {
    
        @Override
        String deserialize(JsonParser parser, DeserializationContext context) {
            parser.hasToken(VALUE_STRING) ? parser.text?.trim() : null
        }
    }
    

提交回复
热议问题