ObjectMapper和ObjectSerializer的使用方法及区别
ObjectMapper和ObjectSerializer
ObjectMapper和ObjectSerializer是两个常用的Java序列化工具,它们的主要区别在于序列化和反序列化的方式以及支持的数据格式。
ObjectMapper是Jackson库中的一个类,用于将Java对象序列化为JSON格式或将JSON格式反序列化为Java对象。它支持多种数据格式,包括JSON、XML、YAML等。ObjectMapper可以将Java对象转换为JSON字符串,也可以将JSON字符串转换为Java对象。使用ObjectMapper时,需要将Jackson库添加到项目的依赖中。
ObjectMapper的使用方法如下:
ObjectMapper objectMapper = new ObjectMapper();
// 将Java对象序列化为JSON字符串
String json = objectMapper.writeValueAsString(obj);
// 将JSON字符串反序列化为Java对象
Object obj = objectMapper.readValue(json, Object.class);
ObjectSerializer是Fastjson库中的一个接口,用于将Java对象序列化为JSON格式或将JSON格式反序列化为Java对象。它只支持JSON格式,并且比ObjectMapper更快,但是在一些特殊情况下可能会存在安全问题。使用ObjectSerializer时,需要将Fastjson库添加到项目的依赖中。
ObjectSerializer的使用方法如下:
ObjectSerializer serializer = new JSONSerializer();
// 将Java对象序列化为JSON字符串
String json = serializer.serialize(obj);
// 将JSON字符串反序列化为Java对象
Object obj = serializer.deserialize(json);
总的来说,ObjectMapper和ObjectSerializer都是常用的Java序列化工具,使用方法类似,但是ObjectMapper支持更多的数据格式,而ObjectSerializer更快。选择使用哪一个工具,需要根据具体的需求和项目情况来决定。
SerializeWriter和ObjectSerializer
SerializeWriter和ObjectSerializer是阿里巴巴的fastjson库中的两个重要类。
SerializeWriter是一个字符流,用于序列化Java对象为JSON格式的字符串。它提供了一些方法,如writeInt,writeString,writeObject等,用于将Java对象的属性写入到JSON字符串中。
ObjectSerializer是一个接口,用于将Java对象序列化为JSON格式的字符串。它定义了一个方法:void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features),其中serializer是JSON序列化器,object是需要序列化的Java对象,fieldName是对象的属性名,fieldType是属性的类型,features是序列化的特性。
在fastjson库中,当需要将Java对象序列化为JSON字符串时,会先创建一个SerializeWriter对象,然后使用ObjectSerializer将Java对象序列化为JSON格式的字符串,并将结果写入SerializeWriter中。最终,SerializeWriter中的字符流就是序列化后的JSON字符串。
ObjectSerializer实现日期格式化
1、自定义类实现ObjectSerializer接口
import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class LocalDateTimeToTimestampSerializer implements ObjectSerializer {
public static final LocalDateTimeToTimestampSerializer instance = new LocalDateTimeToTimestampSerializer();
private static final String defaultPattern = DatePattern.NORM_DATETIME_PATTERN;
public LocalDateTimeToTimestampSerializer() {
}
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
SerializeWriter out = serializer.out;
if (object == null) {
out.writeNull();
} else {
LocalDateTime result = (LocalDateTime) object;
// 转换为yyyy-MM-dd HH:mm:ss格式
out.writeString(result.format(DateTimeFormatter.ofPattern(defaultPattern)));
}
}
}
2、自定义配置类WebMvcConfig实现WebMvcConfigurer,并重写configureMessageConverters方法
package com.midea.fap.aic.query.starter.config;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* @version 1.0
* @description:
* @date 2023-04-26 13:52
*/
@Configuration
@Order(-1)
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
.resourceChain(false);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/swagger-ui/").setViewName("/swagger-ui/index.html");
}
/**
* JSON-转换器
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
converters.removeIf(MappingJackson2HttpMessageConverter.class::isInstance);
SerializeConfig serializeConfig = SerializeConfig.globalInstance;
// 注入自定义LocalDateTime处理器
serializeConfig.put(LocalDateTime.class, LocalDateTimeToTimestampSerializer.instance);
FastJsonConfig config = new FastJsonConfig();
config.setSerializeConfig(serializeConfig);
config.setSerializerFeatures(SerializerFeature.PrettyFormat);
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
fastJsonHttpMessageConverter.setSupportedMediaTypes(getSupportMediaTypes());
fastJsonHttpMessageConverter.setFastJsonConfig(config);
converters.add(fastJsonHttpMessageConverter);
}
/**
* 配置MediaType
* @return List<MediaType>
*/
public static List<MediaType> getSupportMediaTypes() {
List<MediaType> supportMediaTypeList = new ArrayList<>();
supportMediaTypeList.add(MediaType.APPLICATION_JSON);
supportMediaTypeList.add(MediaType.APPLICATION_ATOM_XML);
supportMediaTypeList.add(MediaType.APPLICATION_FORM_URLENCODED);
supportMediaTypeList.add(MediaType.APPLICATION_OCTET_STREAM);
supportMediaTypeList.add(MediaType.APPLICATION_PDF);
supportMediaTypeList.add(MediaType.APPLICATION_RSS_XML);
supportMediaTypeList.add(MediaType.APPLICATION_XHTML_XML);
supportMediaTypeList.add(MediaType.APPLICATION_XML);
supportMediaTypeList.add(MediaType.IMAGE_GIF);
supportMediaTypeList.add(MediaType.IMAGE_JPEG);
supportMediaTypeList.add(MediaType.IMAGE_PNG);
supportMediaTypeList.add(MediaType.TEXT_EVENT_STREAM);
supportMediaTypeList.add(MediaType.TEXT_HTML);
supportMediaTypeList.add(MediaType.TEXT_MARKDOWN);
supportMediaTypeList.add(MediaType.TEXT_PLAIN);
supportMediaTypeList.add(MediaType.TEXT_XML);
return supportMediaTypeList;
}
}