我尝试对 LinkedHashMap 数据进行序列化和反序列化,如下所示:
LinkedHashMap<String, Object> o = new LinkedHashMap<String, Object>();
o.put("1", "a");
o.put("2", "b");
o.put("3", "c");
o.put("4", new BigDecimal("9999999999999999999999.00999999999999999999999"));
String serialize = new JSONSerializer().deepSerialize(o);
System.out.println("serialize" + serialize);
LinkedHashMap deserialize = new JSONDeserializer<LinkedHashMap>().deserialize(serialize, LinkedHashMap.class);
System.out.println("deserialize:" + deserialize);
我得到 ClassCastException:
serialize{"1":"a","2":"b","3":"c","4":9999999999999999999999.00999999999999999999999}
Exception in thread "main" java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.LinkedHashMap
at com.JSONUtil.main(JSONUtil.java:161)
所以我在反序列化时尝试了稍微不同的方法,如下所示:
HashMap deserialize = new JSONDeserializer<HashMap>().deserialize(serialize, HashMap.class);
System.out.println("deserialize:" + deserialize);
这次我得到了结果,但 Map 是无序的(我认为是因为它现在使用的是 HashMap)。此外,BigDecimal 值不像原始格式那样显示。
deserialize:{3=c, 2=b, 1=a, 4=1.0E22}
FlexJSON 似乎对排序的地图有问题。我想这是因为它无法像下面的示例那样放置“类”条目,例如。
"class":"ch.qos.logback.classic.Logger","debugEnabled":true,"errorEnabled":true,"infoEnabled":true}
或者也许还有另一种方法可以做到这一点。有人可以帮忙吗?谢谢
按照chubbsondubs的建议引入ObjectFactory后:
LinkedHashMap deserialize = new JSONDeserializer<LinkedHashMap>()
.use(LinkedHashMap.class, new ObjectFactory() {
public Object instantiate(ObjectBinder context, Object value, Type targetType, Class targetClass) {
System.out.println("mymap:"value);
}
}).deserialize(serialize, LinkedHashMap.class);
值对象具有 HashMap 类型并打印:
mymap:{3=c, 2=b, 1=a, 4=flexjson.JsonNumber@104fc23}