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.
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 asDouble, 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
1to parsed asDouble, another asIntegerand another one asLong; there is no 'right' choice here.If possible you should change the type
Objectto a more specific type such asInteger. If that is not possible you have the following alternatives:GsonBuilder#setObjectToNumberStrategyto specify how Gson should convert a JSON number to anObject.You can use one of the predefined
ToNumberPolicyvariants, or write your ownToNumberStrategy; you can use Gson'sToNumberPolicycode as help for how to do this.Objectfield with@JsonAdapterand create a customTypeAdapterwhich parses the value.