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();
}
}
java JSON格式化工具类
最新推荐文章于 2024-01-16 15:03:59 发布