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

前端 未结 6 1984
别跟我提以往
别跟我提以往 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 07:01

    With a custom deserializer, you could do the following:

     
     @JsonDeserialize(using=WhiteSpaceRemovalSerializer.class)
     public void setAString(String aString) {
        // body
     }
    
     
     public class WhiteSpaceRemovalDeserializer extends JsonDeserializer {
         @Override
         public String deserialize(JsonParser jp, DeserializationContext ctxt) {
             // This is where you can deserialize your value the way you want.
             // Don't know if the following expression is correct, this is just an idea.
             return jp.getCurrentToken().asText().trim();
         }
     }
    

    This solution does imply that this bean attribute will always be serialized this way, and you will have to annotate every attribute that you want to be deserialized this way.

提交回复
热议问题