将JSON字符串转换为HashMap我正在使用Java,我有一个JSON字符串:{"name" : "abc" ,"email id " : ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]}那我的Java地图:Map<String, Object> retMap = new HashMap<String, Object>();我想将JSONObject中的所有数据存储在该HashMap中。任何人都可以为此提供代码吗?我想使用这个org.json库。
3 回答

largeQ
TA贡献2039条经验 获得超7个赞
几天前我通过递归编写了这段代码。
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException { Map<String, Object> retMap = new HashMap<String, Object>(); if(json != JSONObject.NULL) { retMap = toMap(json); } return retMap;}public static Map<String, Object> toMap(JSONObject object) throws JSONException { Map<String, Object> map = new HashMap<String, Object>(); Iterator<String> keysItr = object.keys(); while(keysItr.hasNext()) { String key = keysItr.next(); Object value = object.get(key); if(value instanceof JSONArray) { value = toList((JSONArray) value); } else if(value instanceof JSONObject) { value = toMap((JSONObject) value); } map.put(key, value); } return map;}public static List<Object> toList(JSONArray array) throws JSONException { List<Object> list = new ArrayList<Object>(); for(int i = 0; i < array.length(); i++) { Object value = array.get(i); if(value instanceof JSONArray) { value = toList((JSONArray) value); } else if(value instanceof JSONObject) { value = toMap((JSONObject) value); } list.add(value); } return list;}

有只小跳蛙
TA贡献1824条经验 获得超8个赞
希望这会奏效,试试这个:
import com.fasterxml.jackson.databind.ObjectMapper;Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);
str,你的JSON字符串
如此简单,如果你想要emailid,
String emailIds = response.get("email id").toString();
添加回答
举报
0/150
提交
取消