- //格式一 如//{"username":"7845166313","password":"123456"} 这种格式的解析,返回Map对象。
- public Map<Object,Object> jsonToMapObject(String json){
- Map<Object,Object> map = new HashMap<Object,Object>();//new一个map对象
- String str = json.replace("{","").replace("}","").replaceAll("\\"", "");//去掉大括号、双引号
- String[] ary1 = str.split(",");//根据”,“号分隔字符串,获得数组对象
- for(String s : ary1){//循环取出数组中的对象
- String[] ary2 = s.split(":");//根据”:“冒号分隔字符串,获得键-值数组对象
- map.put(ary2[0],ary2[1]);//将对象以键-值对的方式存入map中
- }
- return map;
- }
- //格式二如://[{"username":"7845166313","password":"123456"},{"username":"545434","password":"3455"},{"username":"45354","password":"345454"}] 数组格式的解析
- public List<Map<Object,Object>> jsonListToObjectList(String json){
- List<Map<Object,Object>> listMap = new ArrayList<Map<Object,Object>>();//实例化一个map类型的集合对象
- String data = json.replaceAll("\\"", "").replace("[{", "").replace("}]","");//去掉前后括号、双引号
- String[]arry = data.split("},\\\\{"); //根据“},{”分隔字符串,获得对象数组
- for(int i=0;i<arry.length;i++){
- String[] arry2 = arry[i].split(",");//以逗号分隔对象("username":"7845166313","password":"123456")
- Map<Object,Object> m = new HashMap<Object,Object>();//实例化map对象
- for(int j=0;j<arry2.length;j++){
- String[] aray3 = arry2[j].split(":");//根据”:“冒号分隔字符串,获得键-值数组对象
- m.put(aray3[0],aray3[1]);//将对象以键-值对的方式存入map中
- }
- listMap.add(m);//将对象存入集合中
- }
- return listMap;
- }
- //该片段来自于http://www.codesnippet.cn/detail/1807201410027.html
来源: http://www.codesnippet.cn/detail/1807201410027.html