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

标签 java spring-boot datetime-format

我有带有日期的模型 (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/

相关文章:

java - 如何设置Scala/Java工作流以通过Jumpserver远程部署jar和进行远程调试?

java - 如何通过改造提取独特的数据

java - 如何一次查询所有/执行器/指标?

MySQL如何插入 '00:65:00'之类的分钟值(大于59分59秒?

asp.net - 将日期字符串转换为日期时间格式 vb.net

java - 重新分配输入/输出流?

java - Clojure 数据结构序列化

hibernate - 当repository.save时Spring Boot + JPA + Hibernate不提交

java - 将 springboot 2.0.1 项目从 payara 4.1.2 移动到 tomcat 8.5.30

java - Scala、SQL Server - 如何使用 Scala 将当前时间戳作为日期时间插入 SQL Server 中?