@JsonSerialize、@JsonDeserialize 与 自定义Converter
Converter 接口可以将一种类型转换为另一种类型。我们可以自定义类型 Converter,然后用 @JsonSerialize#converter
、@JsonDeserialize#converter
指定它们,用于序列化和反序列化。Converter 的类型为com.fasterxml.jackson.databind.util.Converter
。
Example
本例中将转换 LocalDateTime
与格式化的 String
。
Java Object
public class CurrencyRate {
private String pair;
private double rate;
@JsonSerialize(converter = LocalDateTimeToStringConverter.class)
@JsonDeserialize(converter = StringToLocalDatetimeConverter.class)
private LocalDateTime lastUpdated;
...
}
Custom Converters
import com.fasterxml.jackson.databind.util.StdConverter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
public class LocalDateTimeToStringConverter extends StdConverter<LocalDateTime, String> {
static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
@Override
public String convert(LocalDateTime value) {
return value.format(DATE_FORMATTER);
}
}
import com.fasterxml.jackson.databind.util.StdConverter;
import java.time.LocalDateTime;
public class StringToLocalDatetimeConverter extends StdConverter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String value) {
return LocalDateTime.parse(value, LocalDateTimeToStringConverter.DATE_FORMATTER);
}
}
Main class
public class ExampleMain {
public static void main(String[] args) throws IOException {
System.out.println("-- Java object to JSON --");
CurrencyRate cr = new CurrencyRate();
cr.setPair("USD/JPY");
cr.setRate(109.15);
cr.setLastUpdated(LocalDateTime.now());
System.out.println("Java object: " + cr);
ObjectMapper om = new ObjectMapper();
String s2 = om.writeValueAsString(cr);
System.out.println("JSON string: "+s2);
System.out.println("-- JSON to Java object --");
CurrencyRate cr2 = om.readValue(s2, CurrencyRate.class);
System.out.println("Java Object: "+cr2);
}
}
-- Java object to JSON --
Java object: CurrencyRate{pair='USD/JPY', rate=109.15, lastUpdated=2021-04-16T20:24:13.510526700}
JSON string: {"pair":"USD/JPY","rate":109.15,"lastUpdated":"2021年4月16日 下午8:24:13"}
-- JSON to Java object --
Java Object: CurrencyRate{pair='USD/JPY', rate=109.15, lastUpdated=2021-04-16T20:24:13}
原文链接
Jackson JSON - Using @JsonSerialize and @JsonDeserialize with Converter for custom conversion