简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM