安卓工具类jsonString转hashmap

时间:2020-12-28 19:15:23
近来用到一个工具类,网上找了一下没找到合适的,就改了一下。直接可用
importjava.util.ArrayList; importjava.util.HashMap;
importorg.json.JSONArray; importorg.json.JSONException; importorg.json.JSONObject;
public classJsonMapHelper { public static HashMap<String, Object> parseJSONObject(JSONObject jsonobj){ JSONArray a_name = jsonobj.names(); HashMap<String, Object> map =newHashMap<String, Object>(); if(a_name !=null) { inti =0; while(i < a_name.length()) { String key; try{ key = a_name.getString(i); Object obj = jsonobj.get(key); map.put(key,parseUnknowObjectToJson(obj)); }catch(JSONException e) { e.printStackTrace(); } i++; } } returnmap; } public static HashMap<String, Object> parseJSONString(String json) { JSONObject obj; try{ obj =newJSONObject(json); returnparseJSONObject(obj); }catch(JSONException e) { e.printStackTrace(); } return new HashMap<String, Object>(); } public static ArrayList<Object> parseJSONArray(JSONArray jsonarr) { ArrayList<Object> list =newArrayList<Object>(); intlen = jsonarr.length(); for(inti =0; i < len; i++) { Object o; try{ o = jsonarr.get(i); list.add(parseUnknowObjectToJson(o)); }catch(JSONException e) { e.printStackTrace(); } } returnlist; } private static Object parseUnknowObjectToJson(Object o) { if(oinstanceofJSONObject) { returnparseJSONObject((JSONObject)o); } else if (oinstanceofJSONArray) { returnparseJSONArray((JSONArray)o); } returno; } }