Guava Spliter is returning me a Collection but I want a HashMap

时间:2019-04-17 01:59:06

标签: java guava

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!

1 个答案:

答案 0 :(得分:3)

您致电withKeyValueSeparator后,拆分器确实会返回地图。查看{}中的灰色文本,该文本表示map变量的类型是什么。这是实现地图的不可修改的地图。您也会看到该条目集,因为您的IDE会检查不可修改映射的内部实现。

无论哪种方式,我都认为使用专门为解析json构建的库会更好。它可以处理一些极端情况,例如包含冒号的json值。这是一些examples in Jackson