我正在尝试从 HashMap 获取特定值。
我将JsonObject
转换为hashMap
,如下所示:
Map<String, Object> mapObj = new Gson().fromJson(
jsonObject, new TypeToken<HashMap<String, Object>>() {}.getType());
目前一切都很好。
当我尝试从mapObj获取值时 像这样
String strValue = (String) mapObj.get("estimate_time");
它给出 null
我的 Json 是
https://api.myjson.com/bins/16sub7
我真的不知道该怎么办。
最佳答案
“estimate_time”不是有效 key 。它包含在键“data”的值内。
如果您beautified通过您的 json 值,您可以更清楚地注意到键“estimate_time”的值包含在键“data”的值内。
要获取“estimated_time”的值,您需要访问键“data”的 json 值,然后从中访问键“estimated_time”的值。
我以前从未真正使用过Gson
,但以下内容应该可行(或者至少让您了解如何解决该问题)
Map<String, Object> mapObj = new Gson().fromJson(
jsonObject, new TypeToken<HashMap<String, Object>>() {}.getType());
LinkedTreeMap<String, Object> requiredMapObj = (LinkedTreeMap<String, Object>) mapObj.get("data");
String strValue = (String) requiredMapObj.get("estimate_time");
String numberValueAlone = strValue.replaceAll("[^0-9]", "");
( Reference )
关于java - 如何从HashMap中获取特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56925758/