纯Json字符串到HashMap [英] Plain Json String to HashMap

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

问题描述

json转换为HashMap 引发了很多问题。
我希望它可以帮助每个人。

There are quite a few questions raised to convert json to HashMap. I hope it helps everybody.

以下代码将转换值的直接值或 Array ,转换为 HashMap

The following code will convert the direct values or Array of values, into a HashMap.

推荐答案

 private static Map getMap(JSONObject object, String json) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Object jsonObject = null;

        Iterator<String> keys = object.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            Object value = object.get(key);

            if (value instanceof JSONObject) {
                map.put(key, getMap((JSONObject) value, json));
                continue;
            }

         // If value is in the form of array

            if (value instanceof JSONArray) {
                JSONArray array = ((JSONArray) value);
                List list = new ArrayList();
                for (int i = 0 ; i < array.length() ; i++) {
                    jsonObject = array.get(i);
                    if (jsonObject instanceof JSONObject) {
                        list.add(getMap((JSONObject) jsonObject, json));
                    } else {
                        list.add(jsonObject);

                    }
                }
                map.put(key, list);
                continue;
            }

            map.put(key, value);
        }
        return map;
    }

//调用方法

public static Map<String, Object> convertJsonToMap(String json) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject jsonObject = null;

        try {
            if (null != json) {
                jsonObject = new JSONObject(json);
                map = getMap(jsonObject, json);
            }

        } catch (Exception e) {
            throw new SystemException("Unable to read JSOn Object");
            // TODO : Handle Exception
        }
        return map;
    }

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

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