从 JSON 字符串创建哈希映射

2022-08-31 14:53:50

在java中从json字符串创建哈希映射?

我有json字符串,并希望转换为标准的哈希映射。{"phonetype":"N95","cat":"WP"}

我该怎么做?


答案 1

解析 JSONObject 并创建 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}

答案 2

您可以使用Google的Gson库将json转换为Hashmap。试试下面的代码

String jsonString = "Your JSON string";
HashMap<String,String> map = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());