将json数组转换为hashmap< string,object> [英] Convert a json array to an hashmap<string,object>

查看:140
本文介绍了将json数组转换为hashmap< string,object>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an external parsed List type which is a json array, indeed this call

list.toString()

给我这个:

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

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

The content could be anything, an array, a string, an int... So I'd like to map that json array to something like

HashMap<String,Object> converted;

这样我就可以这样做:

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

我怎么能这样做?

推荐答案

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

Try this using JSON Parser. Get the JSON lib from here 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) { }

这篇关于将json数组转换为hashmap&lt; string,object&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆