42-字符串到json 的错误 com.alibaba.fastjson.JSONObject cannot be cast to java.lang.String

时间:2024-07-30 16:36:44

json:

{"updated_at":1551780617,"attr":{"uptime_h":3,"uptime_m":17},"did":"GBBxjJYAxE4apkxwEzR3"}

Map rMap = (Map) JSON.parse("{"updated_at":1551780617,"attr":{"uptime_h":3,"uptime_m":17},"did":"GBBxjJYAxE4apkxwEzR3"} ");

在提取出  rMap.get("attr");  时得到的是:{"uptime_h":3,"uptime_m":17}

但我要得到里面的东西,直接用字符串不好搞,我把它转为json 提取:

Map rMap2 = (Map) JSON.parse((String)rMap.get("attr"));

结果就报错了: com.alibaba.fastjson.JSONObject cannot be cast to java.lang.String

原因是:改map提取出来的对象不能转为String,而要通过它的方法 toString 来转化:

String str = map.get("attr").toString();
System.out.println("ddd===" + str);
Map rMap = (Map) JSON.parse(str);
System.out.println(rMap.get("uptime_h"));

OK!!!