最近在写项目的时候,经常会有String转Object以及Object转Json字符串的需求,或者JSONArray转Lsit以及List转JSONArray的需求,所以抽时间封装一个常用Json工具类。
下面就直接上代码,都是一些在项目中经常用到的转换。
package com.cherry.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* @author [email protected]
* @create 2018/6/14 10:16
* @desc Json工具类
*/
public class JsonTools {
private static final Logger log = LoggerFactory.getLogger(JsonTools.class);
private static ObjectMapper objectMapper = new ObjectMapper();
static {
// 对象字段全部列入
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
// 取消默认转换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("yyyy-MM-dd HH:mm:ss"));
// 忽略在json字符串中存在,但是在java对象中不存在对应属性的情况
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
* object转Json字符串
*
* @param obj
* @param
* @return
*/
public static String obj2String(T obj) {
if (obj == null) {
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.error("Parse object to String error",e);
return null;
}
}
/**
* Object转json字符串并格式化美化
*
* @param obj
* @param
* @return
*/
public static String obj2StringPretty(T obj) {
if (obj == null) {
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Exception e) {
log.error("Parse object to String error",e);
return null;
}
}
/**
* string转object
*
* @param str json字符串
* @param clazz 被转对象class
* @param
* @return
*/
public static T string2Obj(String str, Class clazz) {
if (StringUtils.isEmpty(str) || clazz == null) {
return null;
}
try {
return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
} catch (IOException e) {
log.error("Parse String to Object error",e);
return null;
}
}
/**
* string转object
*
* @param str json字符串
* @param typeReference 被转对象引用类型
* @param
* @return
*/
public static T string2ObjRef(String str, TypeReference typeReference) {
if (StringUtils.isEmpty(str) || typeReference == null) {
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str, typeReference));
} catch (IOException e) {
log.error("Parse String to Object error",e);
return null;
}
}
/**
* string转collection 用于转为集合对象
*
* @param str json字符串
* @param collectionClass 被转集合class
* @param elementClasses 被转集合中对象类型class
* @param
* @return
*/
public static T string2Collection(String str, Class> collectionClass, Class>... elementClasses) {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
try {
return objectMapper.readValue(str, javaType);
} catch (IOException e) {
log.error("Parse String to Collection error",e);
return null;
}
}
/**
* 根据JSONArray String获取到List
*
* @param
* @param
* @param jArrayStr
* @return
*/
public static List getListByJSONArray(Class class1, String jArrayStr) {
List list = new ArrayList<>();
JSONArray jsonArray = JSONArray.parseArray(jArrayStr);
if (jsonArray == null || jsonArray.isEmpty()) {
return list;//nerver return null
}
for (Object object : jsonArray) {
JSONObject jsonObject = (JSONObject) object;
T t = JSONObject.toJavaObject(jsonObject, class1);
list.add(t);
}
return list;
}
/**
* 根据List获取到对应的JSONArray
*
* @param list
* @return
*/
public static JSONArray getJSONArrayByList(List> list) {
JSONArray jsonArray = new JSONArray();
if (list == null || list.isEmpty()) {
return jsonArray;//nerver return null
}
for (Object object : list) {
jsonArray.add(object);
}
return jsonArray;
}
}
Test测试类
@Test
public void obj2String() {
Student student = new Student(1001, "xiaoming", "M", 80.2);
String s = JsonTools.obj2String(student);
System.out.println(s);
}
@Test
public void obj2StringPretty() {
Student student = new Student(1001, "xiaoming", "M", 80.2);
String s = JsonTools.obj2StringPretty(student);
System.out.println(s);
}
@Test
public void string2Obj() {
String s = "{\n" +
" \"id\" : 1001,\n" +
" \"name\" : \"xiaoming\",\n" +
" \"sex\" : \"M\",\n" +
" \"grade\" : 80.2\n" +
"}";
Student student = JsonTools.string2Obj(s, Student.class);
System.out.println(student);
}
@Test
public void string2ObjRef() {
Student xiaoming = new Student(1001, "xiaoming", "M", 80.2);
Student xiaobai = new Student(1002, "xiaobai", "F", 80.3);
List studentList = new ArrayList<>();
studentList.add(xiaoming);
studentList.add(xiaobai);
String studentListStr = JsonTools.obj2StringPretty(studentList);
List studentListObj = JsonTools.string2ObjRef(studentListStr, new TypeReference>() {
});
System.out.println(studentListObj.toString());
}
@Test
public void string2Collection() {
Student xiaoming = new Student(1001, "xiaoming", "M", 80.2);
Student xiaobai = new Student(1002, "xiaobai", "F", 80.3);
List studentList = new ArrayList<>();
studentList.add(xiaoming);
studentList.add(xiaobai);
String studentListStr = JsonTools.obj2StringPretty(studentList);
//List studentListObj = JsonTools.string2ObjRef(studentListStr, new TypeReference>(){});
// 依次传入集合以及集合中对象类型的class
List studentListObj = JsonTools.string2Collection(studentListStr, List.class, Student.class);
System.out.println(studentListObj.toString());
}
@Test
public void getListByJSONArray() {
//定义一个数组
List students = new ArrayList<>();
Student xiaoming = new Student(1001, "xiaoming", "M", 80.2);
Student xiaohong = new Student(1002, "xiaohong", "M", 80.2);
students.add(xiaoming);
students.add(xiaohong);
//将List转换为jsonArray
JSONArray student = JsonTools.getJSONArrayByList(students);
//将jsonArray转为List
List studentList = JsonTools.getListByJSONArray(Student.class, student.toJSONString());
System.out.println(studentList);
}
@Test
public void getJSONArrayByList() {
//定义一个数组
List students = new ArrayList<>();
Student xiaoming = new Student(1001, "xiaoming", "M", 80.2);
Student xiaobai = new Student(1002, "xiaobai", "M", 80.2);
students.add(xiaoming);
students.add(xiaobai);
//将List转换为jsonArray
JSONArray student = JsonTools.getJSONArrayByList(students);
System.out.println(student.toJSONString());
}
pom.xml
org.codehaus.jackson
jackson-mapper-asl
1.9.13