将json数组转换为hashmap <string,object> </string,object>

时间:2014-03-25 19:21:02

标签: java jackson

我有一个外部解析的List类型,它是一个json数组,实际上是这个调用

list.toString()

给了我这个:

[{name=prop1, content=<something>},{name=prop2, content=<something>}]

内容可以是任何内容,数组,字符串,int ... 所以我想将json数组映射到像

这样的东西
HashMap<String,Object> converted;

这将允许我这样做:

converted.get("prop1"); //this will give me the <something>

我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

使用JSON Parser尝试此操作。从这里获取JSON库json.simple

Map<String, Object> map = new HashMap<>();

JSONParser parser = new JSONParser();

try {

  Object obj = parser.parse(list);

  JSONArray jsonArray = (JSONArray)obj;

  Iterator<JSONObject> iterator = jsonArray.iterator();
  while (iterator.hasNext()) {
       JSONObject jsonObj = iterator.next();
      String name = (String) jsonObject.get("name");
       Object content = (Object) jsonObject.get("content");
       map.put(name, content);
  }
} catch (ParseException p) { }