当前位置: 代码迷 >> 综合 >> Springboot @JsonSerialize 相关使用(jsonUtil)
  详细解决方案

Springboot @JsonSerialize 相关使用(jsonUtil)

热度:4   发布时间:2024-02-05 21:24:20.0

基础注解使用

1、实现JsonSerializer接口
例:

public class MySerializerUtils extends JsonSerializer<Integer> {@Overridepublic 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> {@Overridepublic void serialize(Object value, JsonGenerator jsonGenerator,SerializerProvider serializerProvider) throws IOException {jsonGenerator.writeString("");}}
}

2、实现BeanSerializerModifier类

public class CustomizeBeanSerializerModifier extends BeanSerializerModifier {@Overridepublic 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;}/*** 是否是String*/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()));}/*** 将对象转换为Json串,针对String 类型 null 转成""*/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);}}
}

附:jsonUtil完整代码

/*** json串和对象之间相互转换工具类*/
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()));}/*** 将对象转换为Json串*/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);}}/*** 将对象转换为Json串,针对String 类型 null 转成""*/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);}}/*** 将Json串转换为对象*/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);}}/*** 将Json串转换为List*/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);}}/*** 将Json串转换为Map*/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);}}
}