Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw error if strings are not double quoted while using jackson objectmapper deserialization

I have a JSON:

{
    "stringField" : 1234,
    "booleanField": true,
    "numberField": 1200.00
}

I use object mapper to deserialize the json into:-

@Data
class SomeClass {
    String stringField;
    boolean booleanField;
    float numberField;
}

I would like the objectMapper to throw an error because, the values for String fields must be double quoted according to the json spec. How can i get objectMapper to throw an error?

like image 254
Jerald Baker Avatar asked Sep 28 '20 11:09

Jerald Baker


1 Answers

You can write custom string deserializer.(i assume you are using spring)

@Configuration
public class JacksonConfiguration {

    @Bean
    SimpleModule jacksonDeserializerConfiguration() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(String.class, new StdDeserializer<String>(String.class) {
        @Override
        public String deserialize(JsonParser parser, DeserializationContext context)
                throws IOException {
             if (!parser.hasToken(JsonToken.VALUE_STRING)) {
                //throw ex what do u want
                throw new RuntimeException("String not include quote");
            }
            return StringDeserializer.instance.deserialize(parser, context);
        }
    });
        return module;
    }
}
like image 128
divilipir Avatar answered Oct 23 '22 09:10

divilipir