【发布时间】:2017-11-11 14:08:36
【问题描述】:
我们将 SpringBoot 与 Spring Rest 和 Jackson 一起使用。我们使用 Java 8 LocalDateTime。
休息控制器。
@RestController
@RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public class SimpleRestController {
@Autowired
private RestService restService;
@RequestMapping("/api/{id}")
public ResponseEntity<RestObject> getModel(@PathVariable Long id) {
RestObject restObject = restService.getModel(id);
HttpStatus httpStatus = HttpStatus.OK;
if (restObject == null) {
httpStatus = HttpStatus.NO_CONTENT;
}
return new ResponseEntity<>(restObject, httpStatus);
}
}
RestObject 由控制器返回。
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.time.LocalDateTime;
@XmlRootElement
public class RestObject implements Serializable {
private LocalDateTime timestamp;
private String title;
private String fullText;
private Long id;
private Double value;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public LocalDateTime getTimestamp() {
return timestamp;
}
//Other getters and setters.
}
当我发送带有 Accept=application/json 标头的 GET 请求时,它运行良好。这是响应。
{
"timestamp": "2017-06-09 15:58:32",
"title": "Rest object",
"fullText": "This is the full text. ID: 10",
"id": 10,
"value": 0.22816149915219197
}
然而Accept=application/xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<restObject>
<fullText>This is the full text. ID: 10</fullText>
<id>10</id>
<timestamp/>
<title>Rest object</title>
<value>0.15697306201038086</value>
</restObject>
时间戳字段为空。如何让它发挥作用?
【问题讨论】:
-
LocalDateTime 来自 Java 8 还是 jodatime?
-
Java 8 - java.time
-
不支持 Java 8 LocalDateTime。使用 Joda LocalDateTime 或编写转换器。这可能会帮助stackoverflow.com/questions/29424551/…
-
@Hugo 感谢编辑!
标签: java rest spring-boot jackson