Search code examples
javagsondeserializationdata-conversionfromjson

JAVA : On Converting Json Element to an Object, Integer value gets Converted to Double


I have a Class defined with an attribute of Object Data Type

public class Field {
  private Object value = null;
}

On performing below operation

Map<String,Object> map Object = new HashMap<String,Object>();
Field field = new Field();
f1.value = 1;
Map<String, Object> fieldMap = new ObjectMapper().convertValue(field, Field.class);
Gson gson = new GsonBuilder();
JsonElement jsonElement = gson.toJsonTree(fieldMap);
Field field = gson.fromJson(jsonElement, Field.class);

If we access field.value, it returns 1.0 instead of 1. I observed that this conversion happens before the Primitive conversion of GSON. Looks like the Object data type is casting the String in JSON "1" to Double instead of Integer.

Is there any way I can override this default behavior?

I tried using Jackson Convertor instead of GSON, but did not work. I am expecting the response to be an Integer instead of Double value.


Solution

  • The following will be about the part of your code using Gson. In general avoid mixing multiple JSON libraries, either use Gson or Jackson, but not both at the same time (and especially not in the same method). It will just cause confusion and issues, e.g. Jackson annotations not being recognized by Gson and vice versa.


    When you deserialize a JSON number as Object, Gson by default parses it always as Double, regardless of the format of the number.
    Gson does not try to guess the number type because the desired type is application-specific. For example one application might want 1 to parsed as Double, another as Integer and another one as Long; there is no 'right' choice here.

    If possible you should change the type Object to a more specific type such as Integer. If that is not possible you have the following alternatives:

    • Use GsonBuilder#setObjectToNumberStrategy to specify how Gson should convert a JSON number to an Object.
      You can use one of the predefined ToNumberPolicy variants, or write your own ToNumberStrategy; you can use Gson's ToNumberPolicy code as help for how to do this.
    • Annotate the Object field with @JsonAdapter and create a custom TypeAdapter which parses the value.