pom
<!-- jackJson工具-->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>2.0.1</version>
</dependency>
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.databind.type.CollectionType;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
/**
* json格式化工具
*
*/
public class JacksonUtils {
private static ObjectMapper mapper;
private static ObjectMapper getMapper() {
if (mapper == null) {
mapper = new ObjectMapper();
mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
// 如果json中有新增的字段并且是实体类中不存在的。不报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// long转字符串
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
mapper.registerModule(simpleModule);
}
return mapper;
}
/**
* 实体转字符串
* @param value
* @return
*/
public static String writeValueAsString(Object value) {
try {
return getMapper().writeValueAsString(value);
} catch (JsonProcessingException e) {
e.printStackTrace();
return new String();
}
}
/**
* 字符串转实体,实体getset需要无特殊处理
* @param content
* @param valueType
* @param <T>
* @return
*/
public static <T> T readValue(@NotBlank String content, Class<T> valueType) {
try {
return getMapper().readValue(content, valueType);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
public static <T> List<T> readValueToList(String content, Class<T> valueType) {
CollectionType collectionType = getMapper().getTypeFactory().constructCollectionType(ArrayList.class, valueType);
try {
return getMapper().readValue(content, collectionType);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
}