更新时间:2022-10-15 09:14:50
解析的JSONObject和创造的HashMap
公共静态无效jsonToMap(串T)抛出JSONException {
HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
JSONObject的jObject =新的JSONObject(T);
迭代器<>键= jObject.keys();
而(keys.hasNext()){
字符串键=(字符串)keys.next();
字符串值= jObject.getString(密钥);
map.put(键,值);
}
的System.out.println(JSON:+ jObject);
的System.out.println(图:+图)
}
测试输出:
JSON:{phonetype:N95,猫:WP}
图:{phonetype = N95,猫= WP}
creating a hashmap from a json string in java?
I have json string like {"phonetype":"N95","cat":"WP"}
and want to convert into a standard Hashmap.
How can i do it?
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);
}
Tested output:
json : {"phonetype":"N95","cat":"WP"}
map : {phonetype=N95, cat=WP}