gpt4 book ai didi

java - 更改 Spring Boot 应用程序中对象的默认 json

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:10:32 26 4
gpt4 key购买 nike

  • 我有一个简单的 Spring Boot 应用程序,它有一个简单的 MyDateTime 模型类,只有一个具有私有(private)访问权限的 java.util.Date 实例变量、getter/setter 和默认构造函数。

  • Controller 只是实例化这个对象并返回。

  • 在输出中,我看到 Date 对象的默认表示形式是 Integer(可能是来自 Epoch 的 millis)

  • 有什么方法可以将日期对象的默认 jsonification 更改为 ISO 字符串或任何其他字符串?

编辑:

一些说明:

我是 Spring 和 Spring Boot 的新手。我正在使用 spring 网站上示例应用程序的模板。 JSONification 是通过 Jackson 完成的。休息,我对 Spring 总体上了解不多。

最佳答案

您可以在 application.properties 文件中设置 Jackson 在序列化日期时使用的默认格式:

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

http://docs.spring.io/spring-boot/docs/1.2.3.RELEASE/reference/htmlsingle/#common-application-properties

您还可以使用 @JsonFormat 注释指定用于特定日期的特定格式,示例如下:

示例 POJO:

public class Demo {
private Date timestamp1;
private Date timestamp2;
public Date getTimestamp1() {
return timestamp1;
}
public void setTimestamp1(Date timestamp1) {
this.timestamp1 = timestamp1;
}
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ")
public Date getTimestamp2() {
return timestamp2;
}
public void setTimestamp2(Date timestamp2) {
this.timestamp2 = timestamp2;
}
}

示例 Controller :

@RestController
public class DemoController {

@RequestMapping(value="/demo", method = RequestMethod.GET)
Demo start() {
Demo demo = new Demo();
Date timestamp = new Date();
demo.setTimestamp1(timestamp);
demo.setTimestamp2(timestamp);
return demo;
}
}

https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations

关于java - 更改 Spring Boot 应用程序中对象的默认 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29391673/

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