import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
@Slf4j
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
static{
//对象的所有字段全部列入
objectMapper.setSerializationInclusion(Inclusion.ALWAYS);
//取消默认转换timestamps形式
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
//忽略空Bean转json的错误
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
//所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss
objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));
//忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
}
public static String file2String(String filepath) throws IOException {
URL url = JsonUtil.class.getClassLoader().getResource(filepath);
System.out.println(url);
File file = new File(url.getPath());
InputStream in=new FileInputStream(file);//实例化FileInputStream
int fileLength=(int)file.length();
byte b[]=new byte[fileLength];
int length=in.read(b);
in.close();
String s = new String(b);
return s;
}
/**
* 对json字符串进行格式化
* "{\"name\": \"张 三 \", \"remark\": \",: {}[]啦啦啦\", \"data\": [\"1\", \"2\"]}"
* @param content 要格式化的json字符串
* @param indent 是否进行缩进(false时压缩为一行)
* @param colonWithSpace key冒号后是否加入空格
* @return
*/
public static String toFormat(String content, boolean indent, boolean colonWithSpace) {
if (content == null) return null;
StringBuilder sb = new StringBuilder();
int count = 0;
boolean inString = false;
String tab = "\t";
for (int i = 0; i < content.length(); i ++) {
char ch = content.charAt(i);
switch (ch) {
case '{':
case '[':
sb.append(ch);
if (!inString) {
if (indent) {
sb.append("\n");
count ++;
for (int j = 0; j < count; j ++) {
sb.append(tab);
}
}
}
break;
case '\uFEFF': //非法字符
if (inString) sb.append(ch);
break;
case '}':
case ']':
if (!inString) {
if (indent) {
count --;
sb.append("\n");
for (int j = 0; j < count; j ++) {
sb.append(tab);
}
}
sb.append(ch);
} else {
sb.append(ch);
}
break;
case ',':
sb.append(ch);
if (!inString) {
if (indent) {
sb.append("\n");
for (int j = 0; j < count; j ++) {
sb.append(tab);
}
} else {
if (colonWithSpace) {
sb.append(' ');
}
}
}
break;
case ':':
sb.append(ch);
if (!inString) {
if (colonWithSpace) { //key名称冒号后加空格
sb.append(' ');
}
}
break;
case ' ':
case '\n':
case '\t':
if (inString) {
sb.append(ch);
}
break;
case '"':
if (i > 0 && content.charAt(i - 1) != '\\') {
inString = !inString;
}
sb.append(ch);
break;
default:
sb.append(ch);
break;
}
}
return sb.toString();
}
public static <T> String obj2String(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String)obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to String error",e);
return null;
}
}
public static <T> String obj2StringPretty(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to String error",e);
return null;
}
}
public static <T> T string2Obj(String str,Class<T> clazz){
if(StringUtils.isEmpty(str) || clazz == null){
return null;
}
try {
return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
public static <T> T string2Obj(String str, TypeReference<T> typeReference){
if(StringUtils.isEmpty(str) || typeReference == null){
return null;
}
try {
return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
try {
return objectMapper.readValue(str,javaType);
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
}
配套maven
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
DateTimeUtil
package com.my.oasystem.util;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Date;
public class DateTimeUtil {
//joda-time
//str->Date
//Date->str
public static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static Date strToDate(String dateTimeStr,String formatStr){
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
return dateTime.toDate();
}
public static String dateToStr(Date date,String formatStr){
if(date == null){
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(formatStr);
}
public static Date strToDate(String dateTimeStr){
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
return dateTime.toDate();
}
public static String dateToStr(Date date){
if(date == null){
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(STANDARD_FORMAT);
}
public static void main(String[] args) {
System.out.println(DateTimeUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
System.out.println(DateTimeUtil.strToDate("2010-01-01 11:11:11","yyyy-MM-dd HH:mm:ss"));
}
}
注:如忽略时间格式转换可以删除时间工具类,此json工具类只适用于简单实体类与json之间转换,尽量避免驼峰命名