gpt4 book ai didi

java - @JsonSerialize 没有从 Controller springboot 2.2.4 转换我的日期格式

转载 作者:行者123 更新时间:2023-12-01 16:59:51 24 4
gpt4 key购买 nike

我有带有日期的模型 (ModelX)

@Entity
class ModelX
....
@JsonSerialize(using = DateSerializer.class)
private Long date;

日期序列化器

public class JsonDateSerializer extends JsonSerializer<DateTime>
{

private static DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");

@Override
public void serialize(DateTime value, JsonGenerator gen,
SerializerProvider arg2)
throws IOException, JsonProcessingException {

gen.writeString(formatter.print(value));
}
}

我的 Controller

@RestController
public class XC {

@GetMapping(value = "/get/{main_key}"
public get ModelX get(@PathVariable("main_key") String main_key) {
return repository.get(main_key);
}

}

提取有效,但我的日期很长,但我想要一个日期“dd/MM/yyyy”

最佳答案

使用 JSON 自定义序列化程序,您可以格式化长日期

@Entity
class ModelX
....
@JsonSerialize(using = JsonDateCustom.class)
private Long date;

自定义序列化程序

@Component
public class JsonDateCustom extends JsonSerializer<Long> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

@Override
public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
String formattedDate = dateFormat.format(value);
gen.writeString(formattedDate);

}
}

关于java - @JsonSerialize 没有从 Controller springboot 2.2.4 转换我的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61527137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com