Spring JsonDeserializer not working for the type String

我的未来我决定 提交于 2021-02-10 04:56:11

问题


I have a requirement to strip off all the special characters and control characters from the fields of type String in any of the Objects. Deserializer was registered but never executes during the runtime for Strings. I tried adding the same as an annotation @JsonDeserialize(using = StringProcessorComponent.class), but the same issue. It works for any other type like Date/Long. Please let me know if I am missing any.

Here is my Deserializer.

@JsonComponent
public class StringProcessorComponent extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonToken currentToken = p.getCurrentToken();

        if (currentToken.equals(JsonToken.VALUE_STRING)) {
            String text = MyStringProcessor.clean(p.getValueAsString());
            return text;
        }

        return null;
    }
}

回答1:


To override default deserialisers you could use SimpleModule. Also, when you want to extend default implementation if possible you can extend default deserialisers. In your case you can extend com.fasterxml.jackson.databind.deser.std.StringDeserializer class. See below example:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;
import java.util.StringJoiner;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        SimpleModule stringModule = new SimpleModule("String Module");
        stringModule.addDeserializer(String.class, new CustomStringDeserializer());

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(stringModule);

        String json = "{\"firstName\":\"  Tom \",\"lastName\":\"  Long \"}";

        CustomStringPojo customStringPojo = mapper.readValue(json, CustomStringPojo.class);
        System.out.println(customStringPojo);
    }
}

class CustomStringDeserializer extends StringDeserializer {
    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String text = super.deserialize(p, ctxt);
        //clean up value
        return text.trim();
    }
}

class CustomStringPojo {
    private String firstName;
    private String lastName;

    // getters, setters, toString
}

Above code prints:

CustomStringPojo{firstName='Tom', lastName='Long'}


来源:https://stackoverflow.com/questions/60724970/spring-jsondeserializer-not-working-for-the-type-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!