前提:String爲Json類型字符串
maven
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
轉換
Gson gson = new Gson();
Map<String,String> map = new HashMap<>();
JSONObject strJson = JSONObject.fromObject(data);
map= gson.fromJson(strJson.toString(), map.getClass());
注意:
如果map中的value是int,那麼在轉換成json的時候會轉換成Double
如果要使用int,需要進行轉換:
if (!map.isEmpty()) {
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
System.out.println(new Double(String.valueOf(next.getValue())).intValue());
}
}