前言
今天給大家分享的是操作json的工具類,使用的是jackson,如果你使用的是spring boot的話直接引入spring-boot-starter-parent響應的包會自動引入。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>.RELEASE</version>
</parent>
或maven引入
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.2</version>
</dependency>
代碼
package com.zhuma.demo.util;
import java.util.ArrayList;
import java.util.List;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @desc JSON操作工具類
*
* @author zhumaer
* @since 6/20/2017 16:37 PM
*/
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper();
static {
mapper.setSerializationInclusion(Include.NON_NULL);
//設定輸入時忽略JSON字元串中存在而Java對象實際沒有的屬性
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static String object2Json(Object o) {
if (o == null)
return null;
String s = null;
try {
s = mapper.writeValueAsString(o);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
public static <T> List<String> listObject2ListJson(List<T> objects) {
if (objects == null)
return null;
List<String> lists = new ArrayList<String>();
for (T t : objects) {
lists.add(JsonUtil.object2Json(t));
}
return lists;
}
public static <T> List<T> listJson2ListObject(List<String> jsons, Class<T> c) {
if (jsons == null)
return null;
List<T> ts = new ArrayList<T>();
for (String j : jsons) {
ts.add(JsonUtil.json2Object(j, c));
}
return ts;
}
public static <T> T json2Object(String json, Class<T> c) {
if (StringUtils.hasLength(json) == false)
return null;
T t = null;
try {
t = mapper.readValue(json, c);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
@SuppressWarnings("unchecked")
public static <T> T json2Object(String json, TypeReference<T> tr) {
if (StringUtils.hasLength(json) == false)
return null;
T t = null;
try {
t = (T) mapper.readValue(json, tr);
} catch (Exception e) {
e.printStackTrace();
}
return (T) t;
}
}

歡迎關注我們的公衆号或加群,等你哦!