从 JSON 字符串创建 Hashmap [英] creating Hashmap from a JSON String

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

问题描述

从 java 中的 json 字符串创建一个 hashmap?

creating a hashmap from a json string in java?

我有 {"phonetype":"N95","cat":"WP"} 之类的 json 字符串,想转换成标准的 Hashmap.

I have json string like {"phonetype":"N95","cat":"WP"} and want to convert into a standard Hashmap.

我该怎么做?

推荐答案

解析JSONObject并创建HashMap

Parse the JSONObject and create HashMap

public static void jsonToMap(String t) throws JSONException {

        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject jObject = new JSONObject(t);
        Iterator<?> keys = jObject.keys();

        while( keys.hasNext() ){
            String key = (String)keys.next();
            String value = jObject.getString(key); 
            map.put(key, value);

        }

        System.out.println("json : "+jObject);
        System.out.println("map : "+map);
    }

测试输出:

json : {"phonetype":"N95","cat":"WP"}
map : {cat=WP, phonetype=N95}

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

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