13

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.

1
  • 1
    Be clear that JSON is not Gson. JSON is a data format. Gson is a Java library for reading and writing JSON. Commented Jul 19, 2011 at 4:55

1 Answer 1

19

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.