Java jackson配置類,Java jackson工具類,SpringBoot Jackson類配置
================================
©Copyright 蕃薯耀 2021-04-27
https://www.cnblogs.com/fanshuyao/
一、SpringBoot Jackson類配置
SpringBoot 配置ObjectMapper的bean對象,通過增加@ResponseBody返回json對象
使用配置類返回ObjectMapper,而不是在配置文件,可以讓ObjectMapper是同一個,不用在jsonUtils再聲明一個,導致兩處地方可能存在不一致的地方。在jsonUtils直接注入ObjectMapper,保持一致。
import java.text.SimpleDateFormat; import java.util.TimeZone; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.core.json.JsonReadFeature; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @Configuration public class JacksonConfig { @Bean("objectMapper") @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper mapper = builder.build(); // 日期格式 mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); //GMT+8 //map.put("CTT", "Asia/Shanghai"); mapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); // Include.NON_NULL 屬性為NULL 不序列化 //ALWAYS // 默認策略,任何情況都執行序列化 //NON_EMPTY // null、集合數組等沒有內容、空字符串等,都不會被序列化 //NON_DEFAULT // 如果字段是默認值,就不會被序列化 //NON_ABSENT // null的不會序列化,但如果類型是AtomicReference,依然會被序列化 mapper.setSerializationInclusion(Include.NON_NULL); //允許字段名沒有引號(可以進一步減小json體積): mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); //允許單引號: mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true); // 允許出現特殊字符和轉義符 //mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);這個已經過時。 mapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true); //允許C和C++樣式注釋: mapper.configure(Feature.ALLOW_COMMENTS, true); //序列化結果格式化,美化輸出 mapper.enable(SerializationFeature.INDENT_OUTPUT); //枚舉輸出成字符串 //WRITE_ENUMS_USING_INDEX:輸出索引 mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); //空對象不要拋出異常: mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); //Date、Calendar等序列化為時間格式的字符串(如果不執行以下設置,就會序列化成時間戳格式): mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); //反序列化時,遇到未知屬性不要拋出異常: mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //反序列化時,遇到忽略屬性不要拋出異常: mapper.disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); //反序列化時,空字符串對於的實例屬性為null: mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); return mapper; } }
二、Java jackson工具類
ObjectMapper從JacksonConfig配置類注入,使用同一個ObjectMapper
import java.io.IOException; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; /** * Jackson工具類 **/ @Component
@ConditionalOnClass(JacksonConfig.class) public class JsonUtil { private static Logger log = Logger.getLogger(JsonUtil.class); public static ObjectMapper objectMapper; public static ObjectMapper getObjectMapper() { return objectMapper; } //靜態變量注入時,@Autowired注解只能在方法,不能在參數 @Autowired public void setObjectMapper(ObjectMapper objectMapper) { JsonUtil.objectMapper = objectMapper; } /** * Object轉json字符串 */ public static <T> String toJson(T obj) { try { if (obj == null) { return null; }else if (obj instanceof String) { return (String) obj; }else { return objectMapper.writeValueAsString(obj); } } catch (Exception e) { log.error("Parse object to String error", e); return null; } } /** * Object轉json字符串並格式化美化 */ public static <T> String toJsonPretty(T obj) { try { if (obj == null) return null; else if (obj instanceof String) return (String) obj; else return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (Exception e) { log.error("Parse object to String Pretty error", e); return null; } } /** * json轉object */ @SuppressWarnings("unchecked") public static <T> T toBean(String json, Class<T> clazz) { try { if (StringUtils.isEmpty(json) || clazz == null) { return null; }else if(clazz.equals(String.class)){ return (T)json; }else{ return objectMapper.readValue(json, clazz); } } catch (IOException e) { log.error("Parse String to bean error", e); return null; } } /** * json轉集合 * @param <T> * @param json * @param typeReference * <li>new TypeReference<List<User>>() {}</li> * @return */ @SuppressWarnings("unchecked") public static <T> T toBean(String json, TypeReference<T> typeReference) { try { if (StringUtils.isEmpty(json) || typeReference == null) { return null; } else if (typeReference.getType().equals(String.class)) { return (T) json; } else { return objectMapper.readValue(json, typeReference); } } catch (IOException e) { log.error("Parse String to Bean error", e); return null; } } /** * string轉object 用於轉為集合對象 * @param json Json字符串 * @param collectionClass 被轉集合的類 * <p>List.class</p> * @param elementClasses 被轉集合中對象類型的類 * <p>User.class</p> */ public static <T> T toBean(String json, Class<?> collectionClass, Class<?>... elementClasses) { try { JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); return objectMapper.readValue(json, javaType); } catch (IOException e) { log.error("Parse String to Bean error", e); return null; } } }
三、application.properties文件配置jackson返回(使用類配置的方式,可以省略這個)
org.springframework.boot.autoconfigure.jackson.JacksonProperties
#jackson #日期格式化 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss #時區 spring.jackson.time-zone=GMT+8 #格式化輸出 spring.jackson.serialization.indent-output=true #忽略無法轉換的對象 spring.jackson.serialization.fail-on-empty-beans=false #設置空如何序列化 spring.jackson.defaultPropertyInclusion=NON_NULL #允許對象忽略json中不存在的屬性 spring.jackson.deserialization.fail-on-unknown-properties=false #允許出現特殊字符和轉義符 spring.jackson.parser.allow-unquoted-control-chars=true #允許出現單引號 spring.jackson.parser.allow-single-quotes=true
jackson自動裝配類
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
@Configuration(proxyBeanMethods = false) @ConditionalOnClass(Jackson2ObjectMapperBuilder.class) static class JacksonObjectMapperConfiguration { @Bean @Primary @ConditionalOnMissingBean ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { return builder.createXmlMapper(false).build(); } }
理論上,也可以在配置文件配置jackson,然后從spring容器獲取ObjectMapper,在jackson工具類注入該對象,保證使用同一個ObjectMapper對象。
代碼如下:
/** * Jackson工具類 * **/ @Component @ConditionalOnBean(name = "jacksonObjectMapper") public class JsonUtil { //自定義的靜態變量objectMapper private static ObjectMapper objectMapper; public static ObjectMapper getObjectMapper() { return objectMapper; } /** * 先在application.properties配置好jackson的,然后將jacksonObjectMapper注入到自定義的變量objectMapper * @param jacksonObjectMapper */ @Autowired public void setObjectMapper(ObjectMapper jacksonObjectMapper) { JsonUtil.objectMapper = jacksonObjectMapper; } }
(時間寶貴,分享不易,捐贈回饋,^_^)
================================
©Copyright 蕃薯耀 2021-04-27
https://www.cnblogs.com/fanshuyao/