首页 > 代码库 > 将JSON转换成MAP的工具类
将JSON转换成MAP的工具类
package com.xxxx.util;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.URL;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class MapTools { public static List<Map<String, Object>> parseJSON2List(String jsonStr){ JSONArray jsonArr = JSONArray.fromObject(jsonStr); List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); Iterator<JSONObject> it = jsonArr.iterator(); while(it.hasNext()){ JSONObject json2 = it.next(); list.add(parseJSON2Map(json2.toString())); } return list; } public static Map<String, Object> parseJSON2Map(String jsonStr){ Map<String, Object> map = new HashMap<String, Object>(); //最外层解析 JSONObject json = JSONObject.fromObject(jsonStr); for(Object k : json.keySet()){ Object v = json.get(k); //如果内层还是数组的话,继续解析 if(v instanceof JSONArray){ List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); Iterator<JSONObject> it = ((JSONArray)v).iterator(); while(it.hasNext()){ JSONObject json2 = it.next(); list.add(parseJSON2Map(json2.toString())); } map.put(k.toString(), list); } else { map.put(k.toString(), v); } } return map; } public static List<Map<String, Object>> getListByUrl(String url){ try { //通过HTTP获取JSON数据 InputStream in = new URL(url).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while((line=reader.readLine())!=null){ sb.append(line); } return parseJSON2List(sb.toString()); } catch (Exception e) { e.printStackTrace(); } return null; } public static Map<String, Object> getMapByUrl(String url){ try { //通过HTTP获取JSON数据 InputStream in = new URL(url).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while((line=reader.readLine())!=null){ sb.append(line); } return parseJSON2Map(sb.toString()); } catch (Exception e) { e.printStackTrace(); } return null; } //test public static void main(String[] args) { String url = "http://..."; List<Map<String,Object>> list = getListByUrl(url); System.out.println(list); }}
将JSON转换成MAP的工具类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。