java 使用 Gson 将 JSON 字符串解析为 Dictionary<String, Integer>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6737022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse JSON string to Dictionary<String, Integer> with Gson
提问by shorty
I have a JSON string which looks as following: {"altruism":1,"amazon":6}
我有一个 JSON 字符串,如下所示: {"altruism":1,"amazon":6}
What I want to have is a HashMap<String, Integer>
with two entries afterwards.
我想要的是HashMap<String, Integer>
之后有两个条目。
Key: altruism Value: 1
Key: amazon Value:6
I really can't figure out how to do this. Normally there are objects parsed from JSON strings, but that's not the case here.
我真的不知道如何做到这一点。通常有从 JSON 字符串解析的对象,但这里不是这种情况。
回答by Programmer Bruce
Gsonmakes what you're trying to do relatively easy. Following is a working example.
Gson使您尝试做的事情变得相对容易。以下是一个工作示例。
// input: {"altruism":1,"amazon":6}
String jsonInput = "{\"altruism\":1,\"amazon\":6}";
Map<String, Integer> map = new Gson().fromJson(jsonInput, new TypeToken<HashMap<String, Integer>>() {}.getType());
System.out.println(map); // {altruism=1, amazon=6}
System.out.println(map.getClass()); // class java.util.HashMap
System.out.println(map.keySet().iterator().next().getClass()); // class java.lang.String
System.out.println(map.get("altruism").getClass()); // class java.lang.Integer