I am having a hard time with GSON.
I have a simple JSON that I want to deserialize to a Map<String,Object>
.
It's really intuitive to me that 123 should be parsed as an int (or long), 123.4 as a float( or double).
GSON on the other hand creates Doubles all the time.
Can I tell GSON to not abuse double all the time?
My actual code:
Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
GSON gson = new Gson();
Map<String, Object> map = gson.fromJson(someString, mapType);
It sees all kind of numbers as a single type. That the numbers are parsed as a Double is an implementation detail of the Gson library. When it encounters a JSON number, it defaults to parsing it as a Double .
One option is to define a custom JsonDeserializer, however better would be to not use a HashMap (and definitely don't use Hashtable!) and instead give Gson more information about the type of data it's expecting. Show activity on this post. Show activity on this post. Show activity on this post.
Gson can serialize a collection of arbitrary objects but can't deserialize the data without additional information. That's because there's no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type.
Introduction. Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.
The following code compiles & works:
package test;
import java.lang.reflect.Type;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
public class Main {
public static void main(String[] args) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Object.class, new MyObjectDeserializer());
Gson gson = builder.create();
String array = "[1, 2.5, 4, 5.66]";
Type objectListType = new TypeToken<ArrayList<Object>>() {}.getType();
List<Object> obj = gson.fromJson(array, objectListType);
System.out.println(Arrays.toString(obj.toArray()));
}
public static class MyObjectDeserializer implements JsonDeserializer<Object> {
public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
Number num = null;
try {
num = NumberFormat.getInstance().parse(json.getAsJsonPrimitive().getAsString());
} catch (Exception e) {
//ignore
}
if (num == null) {
return context.deserialize(json, typeOfT);
} else {
return num;
}
}
}
}
My solution will first try to parse the string as a number, if that fails it will let the standard Gson deserializer do the work.
If you need a number parser that is not locale specific use this method to parse a number:
private static Number parse(String str) {
Number number = null;
try {
number = Float.parseFloat(str);
} catch(NumberFormatException e) {
try {
number = Double.parseDouble(str);
} catch(NumberFormatException e1) {
try {
number = Integer.parseInt(str);
} catch(NumberFormatException e2) {
try {
number = Long.parseLong(str);
} catch(NumberFormatException e3) {
throw e3;
}
}
}
}
return number;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With