JSONUtils 工具类
package com.xxx.qrcode; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; import net.sf.json.JSONException; import net.sf.json.JSONObject; /** * * @ClassName:JSONUtils * @Description:TODO(这里用一句话描述这个类的作用 JSON工具类) * @author: ZHOUPAN * @date 2018年10月24日 上午11:58:29 * * @Copyright: 2018 www.xxx.com Inc. All rights reserved. */ public class JSONUtils { private static ObjectMapper mapper; /** * 获取ObjectMapper实例 * @param createNew 方式:true,新实例;false,存在的mapper实例 * @return */ public static synchronized ObjectMapper getMapperInstance(boolean createNew) { if (createNew) { return new ObjectMapper(); } else if (mapper == null) { mapper = new ObjectMapper(); } return mapper; } /** * 将java对象转换成json字符串 * @param obj 准备转换的对象 * @return json字符串 * @throws Exception */ public static String beanToJson(Object obj) throws IOException { ObjectMapper objectMapper = getMapperInstance(false); String json =objectMapper.writeValueAsString(obj); return json; } /** * 将java对象转换成json字符串 * @param obj 准备转换的对象 * @param createNew ObjectMapper实例方式:true,新实例;false,存在的mapper实例 * @return json字符串 * @throws Exception */ public static String beanToJson(Object obj,Boolean createNew) throws IOException { ObjectMapper objectMapper = getMapperInstance(createNew); String json =objectMapper.writeValueAsString(obj); return json; } /*** * * @Title: jsonToMap * @Description: TODO(将JSON字符串转为Map) * @author: ZHOUPAN * @param: @param jsonString * JSON字符串 * @param: @throws JSONException * 异常处理 * @return: Map<String,Object> * 返回Map * @throws */ public static Map<String, Object> jsonToMap(String jsonString) throws JSONException { JSONObject jsonObject = JSONObject.fromObject(jsonString); Map<String, Object> result = new HashMap<String, Object>(); Iterator<?> iterator = jsonObject.keys(); String key = null; String value = null; while (iterator.hasNext()) { key = (String) iterator.next(); value = jsonObject.getString(key); result.put(key, value); } return result; } /** * * @Title: jsonToBean * @Description: TODO(将JSON字符创转为Bean) * @author: ZHOUPAN * @param: @param jsonString * @param: @param model * @param: @return * @param: @throws JSONException * @return: T * @throws */ @SuppressWarnings({ "static-access", "unchecked" }) public static <T> T jsonToBean(String jsonString, Class<T> model) throws JSONException { JSONObject jsonObject = JSONObject.fromObject(jsonString); Object object = jsonObject.toBean(jsonObject, model); return (T) object; } }
原文地址:https://www.cnblogs.com/zhou-pan/p/9842808.html
时间: 2024-10-13 02:24:13