0

I'm trying to convert a JSON string (returned on a HTTP Response by a web service) to a HashMap. In Python, I could've simply used json.loads(string_response) and it would've given me a nice dictionary. I'm trying to find a similar thing in Java.

My snippet is-

String result = "{\"packetsReceived_Audio\":\"\",\"packetsReceived_Screen\":\"\",\"packetsReceived_Video\":\"\",\"packetsSent_Audio\":\"\",\"packetsSent_Screen\":\"\",\"packetsSent_Video\":\"\",\"sequenceNumber\":\"0\"}";
Map map = Splitter.on(",").withKeyValueSeparator(":").split(result);

As one of the comments below point out that it should already return a hash map, it really isn't. Its returning me a collection with each item containing sub items - "key" and "value". See attached image for clarity. What I'm expecting is a HashMap.

Debug window from IntelliJ

I know I can add another step to create a usual Map but I wanted to check if there's something available in the framework already.

Thanks!

Sankalp
  • 910
  • 13
  • 20

1 Answers1

3

Splitter does return a map after you callwithKeyValueSeparator. Look at the greyed out text in {}'s which says what is the type of the map variable. It's an unmodifiable map which implements the map. You see the entry set too because your IDE introspects the internal implementation of the unmodifiable map.

Either way I think you would be better off using a library specifically built for parsing json. It would handle corner cases like json values containing colons. Here are some examples in Jackson.

Apokralipsa
  • 2,271
  • 13
  • 22