Raj
Raj

Reputation: 359

Spring JsonDeserializer not working for the type String

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

Upvotes: 3

Views: 2455

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38720

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

Upvotes: 3

Related Questions