Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JSON converts integers into strings

Tags:

java

json

jackson

I am using the object mapper to map into an object that has String variables. This works a little too well, because even integers and booleans from the JSON are converted into Strings. Example:

{"my_variable":123}

class MyClass{
    String my_variable;
}

I would like the object mapper to report an error in this kind of situation instead of converting 123 into a string for my_variable. Is this possible?

like image 549
Joonas Avatar asked Oct 18 '11 11:10

Joonas


People also ask

How does Jackson convert object to JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.


1 Answers

There is currently no such configuration, but you can override default deserializer with a custom one (see fasterxml wiki) and make that throw an exception?

If you would like a more convenient way you can file a Jira enhancement request; for example, new DeserializationConfig.Feature.COERCE_STRINGS_AS_NUMBERS (default to true) that one could disable to prevent such coercion.

like image 57
StaxMan Avatar answered Oct 02 '22 04:10

StaxMan