我对GSON很难过.
我有一个简单的JSON,我想反序列化为Map< String,Object>.
我真的很直观,123应该被解析为int(或long),123.4作为float(或double).
另一方面,GSON一直创造双打.
我可以告诉GSON不要一直滥用双倍?
我的实际代码:
Type mapType = new TypeToken<Map<String,Object>>() {}.getType(); GSON gson = new Gson(); Map<String,Object> map = gson.fromJson(someString,mapType);
解决方法
以下代码编译&作品:
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; } } } }
我的解决方案将首先尝试将字符串解析为数字,如果失败则会让标准的Gson解串器完成工作.
如果需要非特定于语言环境的数字解析器,请使用此方法解析数字:
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; }