2015-07-11 53 views
1

我有JSON对象是这样的:如何使用jackson将JSON数组解析为HashMap?

"stream_server":{ 
     "value":"11", 
     "list":[ 
      { 
       "id":"11", 
       "desc":"EU West" 
      }, 
      { 
       "id":"4", 
       "desc":"EU Sud + GB" 
      }, 
      { 
       "id":"9", 
       "desc":"DE 1" 
      }, 
      { 
       "id":"12", 
       "desc":"DE 2" 
      } 
     ] 
     } 

我生成的代码为杰克逊库,其中“列表”是作为对象的ArrayList

public class StreamServer { 
    @JsonProperty("value") 
    private String value; 
    @JsonProperty("list") 
    private java.util.HashMap<String, String> serverList = new HashMap<>(); 
} 

我可以将它反序列化为如上所述的Java对象吗?

我在查找示例代码。

+0

做üGOOGLE了它? – Bikku

+0

可能重复[反序列化到与杰克逊自定义对象的HashMap](http://stackoverflow.com/questions/18002132/deserializing-into-a-hashmap-of-custom-objects-with-jackson) – Bikku

+0

@ GoodBadandUgly,感谢您的链接。也许它会帮助我。但这绝不是我的情况。例如,“id”的值“11”是关键,“desc”的值“EU West”是我的HashMap的值。在你的例子中,“id”是关键,“11”是价值,“desc”是关键“EU West”是价值等等。希望,这听起来不是太复杂 – Sartre

回答

3

您可以将其反序列化为。

public static class StreamServer { 
    @JsonProperty("value") 
    private String value; 

    @JsonProperty("list") 
    private List<Server> serverList; 

} 

public static class Server { 
    @JsonProperty("id") 
    private String id; 

    @JsonProperty("desc") 
    private String desc; 
} 

杰克逊代码阅读会像下面的东西:

ObjectMapper m = new ObjectMapper(); 
    StreamServer s = m.readValue(json, StreamServer.class); 
+0

我明白了,但List <>是多余的。 – Sartre

+1

在你的JSON结构中,列表是一个列表,而不是一个Map,列表中的每个成员都是一个Map(或者一个json对象 - 取决于你如何看待它)。 –

+0

因此,我不能将“id”的值用作HashMap的键值,将“desc”的值用作HashMap的值? – Sartre