GSON到HashMap中GSON、HashMap

2023-09-03 20:56:05 作者:樱花落ゞ谁懂殇°

有没有办法来包含JSON到一个HashMap,在每一个关键是一个JSON-key和value是JSON-键值字符串转换? JSON的没有嵌套值。我现在用的是GSON库。

Is there a way to convert a String containing json to a HashMap, where every key is a json-key and the value is the value of the json-key? The json has no nested values. I am using the Gson lib.

例如,给出JSON:

{
"id":3,
"location":"NewYork"
}

造成的HashMap:

resulting HashMap:

<"id", "3">
<"location", "NewYork">

感谢

推荐答案

使用TypeToken,按the GSON常见问题解答:

Gson gson = new Gson();
Type stringStringMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(json, stringStringMap);

没有铸造。没有不必要的对象的创建。

No casting. No unnecessary object creation.