将JSON字符串转换为HashMap [英] Convert a JSON String to a HashMap

查看:815
本文介绍了将JSON字符串转换为HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Java,我有一个String是JSON:

I'm using Java, and I have a String which is JSON:

{
"name" : "abc" ,
"email id " : ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]
}

我有一个Java地图:

And I have a Map in Java:

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

我想将JSON中的所有数据存储在该HashMap中。

I want to store all the data from the JSONObject in that HashMap.

任何人都可以为此提供代码?我想使用'org.json'库。

Can anyone provide code for this? I want to use the 'org.json' library.

推荐答案

>

I wrote this code some days back by recursion.

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;
}

这篇关于将JSON字符串转换为HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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