Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 strings, but that's not the case here.

like image 302
shorty Avatar asked Jul 18 '11 17:07

shorty


1 Answers

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
like image 97
Programmer Bruce Avatar answered Oct 04 '22 02:10

Programmer Bruce