开发者

Parse JSON string to Dictionary<String, Integer> with Gson

I have a JSON string which looks as following: {"altruism":1,"amazon":6}

What I want to have is a HashMap<String, Integer> with two entries afterwards.

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开发者_JAVA百科 strings, but that's not the case here.


Gson makes what you're trying to do relatively easy. Following is a working example.

// 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜