Python 官方文档:入门教程 => 点击学习
目录@JSONSerialize的使用讲解1.写一个类继承jsonSerializer 抽象类2.然后在传输的实体类中的属性上3.附加:还有一个比较好用的注解4.附加:之前附件3的注
解决前端显示和后台存储数据单位不一致的问题。
在返回对象时,进行自定义数据格式转换。
实现其serialize()方法,然后在方法中写入转换规则即可
举例是把Date时间戳从 毫秒 转换成 秒 为单位
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Date;
public class Date2LongSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(date.getTime() / 1000);
}
}
打上@JsonSerialize注解即可
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.ls.sell.enums.OrderStatusEnum;
import com.ls.sell.enums.PayStatusEnum;
import com.ls.sell.util.serializer.Date2LongSerializer;
import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.util.Date;
@Entity
@Data
@DynamicUpdate
public class OrderMaster {
@Id
private String orderId;
private String buyerName;
private String buyerPhone;
private String buyerAddress;
private String buyerOpenid;
private BigDecimal orderAmount;
private Integer orderStatus = OrderStatusEnum.NEW.getCode();
private Integer payStatus = PayStatusEnum.WaiT.getCode();
@JsonSerialize(using = Date2LongSerializer.class)
private Date createTime;
@JsonSerialize(using = Date2LongSerializer.class)
private Date updateTime;
}
如果返回对象中变量存在null,可以使用@JsonInclude(JsonInclude.Include.NON_NULL)注解来忽略为null的变量,这样前端比较好处理
package com.ls.sell.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.ls.sell.entity.OrderDetail;
import com.ls.sell.entity.OrderMaster;
import lombok.Data;
import java.util.List;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class OrderDTO extends OrderMaster {
private List<OrderDetail> orderDetailList;
}
使用注解之前的返回值:
使用注解之后:
还是比较好用的。
如果一个一个实体类配置的话,未免太过麻烦,所以可以在配置文件中直接配置,yml配置文件如下:
1、实现JsonSerializer接口
例:
public class MySerializerUtils extends JsonSerializer<Integer> {
@Override
public void serialize(Integer status, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
String statusStr = "";
switch (status) {
case 0:
statusStr = "新建状态";
break;
}
jsonGenerator.writeString(statusStr);
}
}
2、添加注解
注:@JsonSerialize注解,主要应用于数据转换,该注解作用在该属性的getter()方法上。
①用在属性上(自定义的例子)
@JsonSerialize(using = MySerializerUtils.class)
private int status;
②用在属性上(jackson自带的用法)
@JsonFORMat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime sendTime;
③用在空对象上可以转化
@JsonSerialize
public class XxxxxBody {
// 该对象暂无字段,直接new了返回
}
jsonUtil工具类
实现json转换时所有的null转为“”
1、实现JsonSerializer类
public class CustomizeNullJsonSerializer {
public static class NullStringJsonSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
}
}
2、实现BeanSerializerModifier类
public class CustomizeBeanSerializerModifier extends BeanSerializerModifier {
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties) {
for (int i = 0; i < beanProperties.size(); i++) {
BeanPropertyWriter writer = beanProperties.get(i);
if (isStringType(writer)) {
writer.assignNullSerializer(new CustomizeNullJsonSerializer.NullStringJsonSerializer());
}
}
return beanProperties;
}
private boolean isStringType(BeanPropertyWriter writer) {
Class<?> clazz = writer.getType().getRawClass();
return CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz);
}
}
3、工具类调用
public class JsonUtil {
//序列化时String 为null时变成""
private static ObjectMapper mapperContainEmpty = new ObjectMapper();
static {
mapperContainEmpty.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapperContainEmpty.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapperContainEmpty.setSerializerFactory(mapperContainEmpty.getSerializerFactory()
.withSerializerModifier(new CustomizeBeanSerializerModifier()));
}
public static String toJsonContainEmpty(Object o) {
try {
return mapperContainEmpty.writeValueAsString(o);
} catch (IOException e) {
logger.error("render object to json error: {}", e.getMessage(), e);
throw new RuntimeException("render object to json error!", e);
}
}
}
public class JsonUtil {
private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
private static ObjectMapper mapper = new ObjectMapper();
//序列化时String 为null时变成""
private static ObjectMapper mapperContainEmpty = new ObjectMapper();
static {
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(Include.NON_NULL);
mapperContainEmpty.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapperContainEmpty.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapperContainEmpty.setSerializerFactory(mapperContainEmpty.getSerializerFactory()
.withSerializerModifier(new CustomizeBeanSerializerModifier()));
}
public static String toJson(Object o) {
try {
return mapper.writeValueAsString(o);
} catch (IOException e) {
logger.error("render object to json error: {}", e.getMessage(), e);
throw new RuntimeException("render object to json error!", e);
}
}
public static String toJsonContainEmpty(Object o) {
try {
return mapperContainEmpty.writeValueAsString(o);
} catch (IOException e) {
logger.error("render object to json error: {}", e.getMessage(), e);
throw new RuntimeException("render object to json error!", e);
}
}
public static <T> T toObject(String json, Class<T> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (IOException e) {
logger.error("render json to object error: {}", e.getMessage(), e);
throw new RuntimeException("render json to object error!", e);
}
}
public static <T> List<T> toList(String json, Class<T> clazz) {
try {
JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, clazz);
return mapper.readValue(json, javaType);
} catch (IOException e) {
logger.error("render json to List<T> error: {}", e.getMessage(), e);
throw new RuntimeException("render json to List<T> error!", e);
}
}
public static <K, V> Map<K, V> toMap(String json, Class<K> clazzKey, Class<V> clazzValue) {
try {
JavaType javaType = mapper.getTypeFactory().constructParametricType(Map.class, clazzKey, clazzValue);
return mapper.readValue(json, javaType);
} catch (IOException e) {
logger.error("render json to Map<K, V> error: {}", e.getMessage(), e);
throw new RuntimeException("render json to Map<K, V> error!", e);
}
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: springboot @JsonSerialize的使用讲解
本文链接: https://lsjlt.com/news/137877.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0