public static void main(String[] args) {
Gson g = new GsonBuilder()
.setPrettyPrinting()
.enableComplexMapKeySerialization()
.serializeSpecialFloatingPointValues()
.setLongSerializationPolicy(LongSerializationPolicy.DEFAULT)
.setPrettyPrinting()
//.registerTypeAdapter(HashMap.class, new HashMapDeserializer())
.create();
HashMap<Object, Object> h = new HashMap<Object, Object>();
h.put("num1", 10);
h.put("num2", 20);
h.put("num3", 20.0);
h.put("num4", "<>");
h.put("num5", "~!@#$%^&*()_+=-`,.<>?/:;[]{}|");
String jsonStr = g.toJson(h);
System.out.println("JsonString::"+jsonStr);
/*Output below ::
*
JsonString::{
"num4": "\u003c\u003e",
"num5": "~!@#$%^\u0026*()_+\u003d-`,.\u003c\u003e?/:;[]{}|",
"num2": 20,
"num3": 20.0,
"num1": 10
}
*/
h = g.fromJson(jsonStr, HashMap.class);
System.out.println("convert from json String :>"+h);
/*Output below:
convert from json String :>{num4=<>, num5=~!@#$%^&*()_+=-`,.<>?/:;[]{}|, num2=20.0, num3=20.0, num1=10.0}
*/
int num1= (Integer) h.get("num1");
System.out.println(num1);
}
Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
at com.ps.multiupload.servlet.FileUploadUtil.main(FileUploadUtil.java:52)
答案 0 :(得分:1)
要序列化混合类型哈希映射,请创建一个知道所需类型的Java类:
class NumNumNum {
int num1;
int num2;
double num3;
String num4;
String num5;
}
将JSON反序列化为类似的类将为Gson提供所需的提示。只需Map<Object, Object>
,它就是最简单的事情。
答案 1 :(得分:0)
试试这个:
int num1=new Integer(h.get("num1").toString());
float num3=new Float(h.get("num3").toString());
答案 2 :(得分:0)
不幸的是,这不是那么简单。您需要创建自己的反序列化器。我建议您从源代码中复制粘贴以下类:ObjectTypeAdapter,MapTypeAdapterFactory和aux类TypeAdapterRuntimeTypeWrapper。现在通过替换以下行来修复MapTypeAdapterFactory.create方法:
TypeAdapter<?> valueAdapter = gson.getAdapter(TypeToken.get(keyAndValueTypes[1]));
带
TypeAdapter<?> valueAdapter = MyObjectTypeAdapter.FACTORY.create(gson, TypeToken.get(keyAndValueTypes[1]));
现在通过替换以下行来修复ObjectTypeAdapter.read方法:
case NUMBER:
return in.nextDouble();
带
case NUMBER:
return in.nextLong();
最后一件事:在gson中注册自定义地图序列化器:
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapterFactory(new MyMapTypeAdapterFactory(new ConstructorConstructor(Collections.<Type, InstanceCreator<?>>emptyMap()), false))
.create();
现在JSON中的任何“NUMBER”数据都会被反序列化为long。