I have the following JSON sample:
{
"channel": "VTEX",
"data": "{}",
"refId": 143433.344,
"description": "teste",
"tags": ["tag1", "tag2"]
}
That should map to the following class:
public class AddConfigInput {
public String channel;
public String data;
public String refId;
public String description;
public String[] tags;
public AddConfigInput() {
}
}
Using a code like bellow:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
String json = STRING_CONTAINING_THE_PREVIOUS_INFORMED_JSON;
AddConfigInput obj = mapper.readValue(json, AddConfigInput.class);
System.out.println(mapper.writeValueAsString(obj));
That produces as output:
{"channel":"VTEX","data":"{}","refId":"143433.344","description":"teste","tags":["tag1","tag2"]}
Please note that the field refId is of type String and I want to avoid this kind of automatic conversion from Numbers to String properties. Instead I want to Jackson throws an error about the type mismatch. How can I do that?
It seems that
mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
works for the reverse case, that is, parsing fails when deserializingString
value to numeric field.Providing custom deserializer for the
refId
field seems to resolve this issue.Update
This custom deserializer may be registered within the
ObjectMapper
and override default behaviour:Then this module can be registered with
ObjectMapper
:After modifying slightly the input JSON (using boolean for
data
field which must be String), the following exception is thrown: