欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

json转换工具类

程序员文章站 2024-03-18 18:41:34
...
import java.io.BufferedReader;
import java.io.IOException;
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 java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
* @author leon
* @createDate 2018年5月14日 下午3:21:06
* @version v1.0
* @classRemarks json工具类
*/
public class JsonUtils {

	private static final ObjectMapper objectMapper = new ObjectMapper();
	/*** 编码 */
	private static final String CHAR_ENCODING = "UTF-8";

	private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);

	/**
	 * 将 Java 对象转为 JSON 字符串
	 */
	public static String obj2JSON(Object obj) {
		String jsonStr;
		try {
			jsonStr = objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			logger.error("Java 转 JSON 出错!", e);
			throw new RuntimeException(e);
		}
		return jsonStr;
	}

	/**
	 * 将 JSON 字符串转为 Java 对象
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <T> T json2Object(String json, Class type) {
		T obj;
		try {
			obj = (T) objectMapper.readValue(json, type);
		} catch (Exception e) {
			logger.error("JSON 转 Java 出错!", e);
			throw new RuntimeException(e);
		}
		return obj;
	}

	/**
	 * json串 转map
	 * 
	 * @param jsonStr
	 * @return
	 */
	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;
	}
	
	/**
	 * Json转map和List<Map<String,Object>>
	 * 
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> parseJSON2Listmap(String jsonStr) {
		// Gson gson = new Gson();
		ObjectMapper objectMapper = new ObjectMapper();
		List<Map<String, Object>> newMap = null;
		try {
			newMap = objectMapper.readValue(jsonStr, List.class);
		} catch (Exception e) {
			logger.error("系统错误:",e);
		}
		//System.out.println(newMap);
		return newMap;
	}

	/**
	 *
	 * 通过HTTP获取JSON数据. <br>
	 * 通过HTTP获取JSON数据返回list
	 * 
	 * @param url
	 *            链接
	 * @return
	 * @return List<Map<String,Object>> list
	 * @throws @author
	 *             slj
	 */
	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 parseJSON2Listmap(sb.toString());
		} catch (Exception e) {
			logger.error("系统错误:",e);
		}
		return null;
	}

	/**
	 *
	 * 通过HTTP获取JSON数据. <br>
	 * 通过HTTP获取JSON数据返回map
	 * 
	 * @param url
	 *            链接
	 * @return
	 * @return Map<String,Object> 集合
	 * @throws @author
	 *             slj
	 */
	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) {
			logger.error("系统错误:",e);
		}
		return null;
	}

	/**
	 *
	 * map转换json.
	 * @param map 集合
	 * @return
	 */
	public static String mapToJson(Map<String, String> map) {
		Set<String> keys = map.keySet();
		String key = "";
		String value = "";
		StringBuffer jsonBuffer = new StringBuffer();
		jsonBuffer.append("{");
		for (Iterator<String> it = keys.iterator(); it.hasNext();) {
			key = (String) it.next();
			value = map.get(key);
			jsonBuffer.append(key + ":" + "\"" + value + "\"");
			if (it.hasNext()) {
				jsonBuffer.append(",");
			}
		}
		jsonBuffer.append("}");
		return jsonBuffer.toString();
	}
	
	/**
	 * 返回json格式的数据
	 * 
	 * @param response
	 * @param jsonObject
	 */
	public static void doJsonResponse(HttpServletResponse response,
			final JSONObject jsonObject) {
		response.setCharacterEncoding(CHAR_ENCODING);
		response.setContentType("application/json; charset=utf-8");  
		try {
			response.getWriter().print(jsonObject);
		} catch (IOException e) {
			logger.error(e.getMessage());
			logger.error("系统错误:",e);
		}
	}

}

 

相关标签: json json转换