我与 jackson 有以下代码:
public class Header implements Serializable {
@JsonProperty("numeroUnico")
private Integer numeroCliente;
@JsonProperty("oficina")
private Integer oficina;
@JsonProperty("fecha")
@JsonSerialize(using = CustomDateSerializer.class)
private Date fechaInscripcion;
}
这是我的类(class)“CustomDateSerializer.class”
public class CustomDateSerializer extends StdSerializer<Date> {
private SimpleDateFormat formatter
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public CustomDateSerializer() {
this(null);
}
public CustomDateSerializer(Class t) {
super(t);
}
@Override
public void serialize (Date value, JsonGenerator gen, SerializerProvider arg2)
throws IOException, JsonProcessingException {
gen.writeString(formatter.format(value));
}
}
他们要求我将 Jackson 的所有实现迁移到 Gson。 考虑到 Jackson @JsonProperty 中的表示法在 Gson 中具有等效的 @SerializedName。 但对于 jackson 的符号:
@JsonSerialize (using = CustomDateSerializer.class)
Gson 的等价物是什么?如果不是,因为它应该是我的 DTO 中 Date 类型的属性的实现。
最佳答案
我认为最接近且可能是唯一的匹配是 @TypeAdapter
。但是您需要编码 JsonSerializer<T>
或 TypeAdapter<T>
与该注释一起使用。
例如,如何制作类似 CustomDateSerializer
的内容请参阅 this question 已接受的答案.
或者也许您可以包装现有的 CustomDateSerializer
与 Gson TypeAdapter<Date>
并在注释中使用它。
关于java - 属性 DTO 中格式化日期的符号 Gson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52991714/