日常踩坑
错误示范
public static void main(String[] args) {
String studentJson= "{\"name\":\"张三\",\"age\":18,\"extraJson\":{\"height\":185,\"weight\":80}}";
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(studentJson);
if (map != null) {
System.out.println("map:"+map);
System.out.println("map.get(\"extraJson\").getClass():"+map.get("extraJson").getClass());
String extraJson= (String)map.get("extraJson");
System.out.println("extraJson:"+extraJson);
}else{
System.out.println("map为null");
}
}
错误示范输出结果:
map.get("extraJson").getClass():class com.alibaba.fastjson.JSONObject
Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to java.lang.String
正确示范
public static void main(String[] args) {
String studentJson= "{\"name\":\"张三\",\"age\":18,\"extraJson\":{\"height\":185,\"weight\":80}}";
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(studentJson);
if (map != null) {
System.out.println("map:"+map);
System.out.println("map.get(\"extraJson\").getClass():"+map.get("extraJson").getClass());
String extraJson= map.get("extraJson").toString();
System.out.println("extraJson:"+extraJson);
}else{
System.out.println("map为null");
}
}
正确示范输出结果:
map.get("extraJson").getClass():class com.alibaba.fastjson.JSONObject
extraJson:{"height":185,"weight":80}
坑的原因:
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(studentJson);
这里使用强转时,value值类型并没有转化为Object,而是JSONObject,所以再通过String强转就会报错,而通过JSONObject自带的toString却不会。
版权声明:本文为qq_38081900原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。