java JSON格式化工具类

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import com.ac.intellsecurity.utils.document.excel.OSinfo;
import com.ac.intellsecurity.utils.document.word.DocumentHandler;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * JSON格式化工具类
 * @author MaChao 2017.10.17 create
 *
 */
public class JsonUtil {

	private static ObjectMapper objectMapper = null;
	//获取格式化类
	private static ObjectMapper getObjectMapper(){
		if(objectMapper == null){
			objectMapper = new ObjectMapper();  
			//去掉默认的时间戳格式  
			objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);  
			//设置为中国上海时区  
			objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));  
			objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);  
			//空值不序列化  
			//objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);  
			//反序列化时,属性不存在的兼容处理  
			objectMapper.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);  
			//序列化时,日期的统一格式  
			objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));  
			objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);  
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);  
			//单引号处理  
			objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); 			
		}
		return objectMapper;
	}
	
	/**
	 * JSON字符串转MAP对象
	 * @param jsonStr
	 * @return
	 */
	public static Map<String,Object> jsonStrToMap(String jsonStr){
		try {
			if(jsonStr == null){
				return null;
			}
			return getObjectMapper().readValue(jsonStr,new TypeReference<Map<String,Object>>(){ });
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * map 转jsonString
	 * @param map
	 * @return
	 */
	public static String mapToJsonStr(Map<?, ?> map){
		try {
			return getObjectMapper().writeValueAsString(map);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * list转jsonString
	 * @param list
	 * @return
	 */
	public static String listToJsonStr(List<?> list){
		try {
			return getObjectMapper().writeValueAsString(list);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * jsonString转bean
	 * @param <T>
	 * @param json
	 * @return
	 */
	public static <T> T jsonStrToBean(String json,Class<T> classs){
		
		try {
			return getObjectMapper().readValue(json, classs);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * jsonString转list
	 * @param <T>
	 * @param list
	 * @return
	 */
	public static <T> List<T> jsonStrToList(String json,Class<T> classs){
		JavaType javaType = getCollectionType(ArrayList.class, classs);
		if(json == null){
			return null;
		}
		try {
			return getObjectMapper().readValue(json, javaType);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String beanToJson(Object bean){

		try {
			return getObjectMapper().writeValueAsString(bean);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static Map<String,Object> beanToMap(Object bean){
		Map<String,Object> map=new HashMap<>();
		BeanInfo info;
		try {
			info = Introspector.getBeanInfo(bean.getClass(),Object.class);
			PropertyDescriptor[]pds=info.getPropertyDescriptors();
			for(PropertyDescriptor pd:pds) {
				String key=pd.getName();
				Object value;
				value = pd.getReadMethod().invoke(bean);
				map.put(key, value);
			}
		} catch (IntrospectionException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**   
	* 获取泛型的Collection Type  
	* @param collectionClass 泛型的Collection   
	* @param elementClasses 元素类   
	* @return JavaType Java类型   
	*/   
	public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
		return getObjectMapper().getTypeFactory().constructParametrizedType(collectionClass ,collectionClass ,elementClasses);
	}
	
	/**   
	* @Title: JSON2Map  
	* @Description:将json格式封装的字符串数据转换成java中的Map数据
	* @param @param jsonMapStr
	* @param @return      
	* @return Map
	* @author 李海龙
	* @throws
	*/ 
	public  static Map JSON2Map(String jsonMapStr,HttpServletRequest request) {
//		String rootPath = request.getSession().getServletContext().getRealPath("/");
//		ServletContext rootPath1 = request.getSession().getServletContext();
//		if(rootPath.substring(rootPath.length()-1,rootPath.length()).equals("\\")){
//			rootPath=rootPath.substring(0,rootPath.length()-1);
//			rootPath=rootPath.substring(0,rootPath.lastIndexOf("\\"))+"\\";
//		}
//		rootPath = rootPath.replace("IntellSecurity-Web\\", "");
		Properties prop = new Properties();
		try {
			prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String realPath = "";
		if(OSinfo.isLinux()){
			realPath = prop.getProperty("realPath.linux");
		}else {
			realPath = prop.getProperty("realPath.windows");
		}
	    Map map = new HashMap();
        JSONObject jsonmap = JSONObject.parseObject(jsonMapStr);
        jsonmap.keySet();
	    Set<String> it = jsonmap.keySet();
	    DocumentHandler documentHandler = new DocumentHandler();
	    for (String key : it) {  
	        String value = jsonmap.getString(key);
	        if (value.contains("files/upload/imgs/img"+File.separator)||value.contains("files/upload/imgs/img")) {
	        	int positionOfF = getCharacterPosition(value);
//	        	String filePath = value.substring(positionOfF,value.length());
	        	value = value.replace("files/", realPath);
	        	value = value.replace("\\", "/");
				map.put(key,documentHandler.getImageStr(value));
			}else {
				map.put(key, value);  
			}
	    }  
	    return map;
	} 

	private static final Pattern pattern = Pattern.compile("/");

	public static int getCharacterPosition(String string){
	    //这里是获取"/"符号的位置
	    Matcher slashMatcher = pattern.matcher(string);
	    int mIdx = 0;
	    while(slashMatcher.find()) {
	       mIdx++;
	       //当"/"符号第三次出现的位置
	       if(mIdx == 3){
	          break;
	       }
	    }
	    return slashMatcher.start();
	 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值