Java – enables gson to deserialize numbers to integers or doubles
•
Java
I'm sorry for gson
I have a simple JSON. I want to deserialize it into map < string, Object >
I'm really intuitive. 123 should be parsed as int (or long) and 123.4 as float (or double)
On the other hand, gson has been creating doubles
Can I tell gson not to 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);
Solution
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 strings into numbers, and if it fails, it will let the standard gson deserializer complete its work
If you need a locale neutral number parser, use this method to parse numbers:
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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
