【发布时间】:2019-03-24 00:57:52
【问题描述】:
我在 spring boot + kotlin 中创建了一个 POST API。我创建了一个 LocalDate 对象,但不需要响应。我用过
org.springframework.format.annotation.DateTimeFormat
我得到的是这样的:
<user>
<email>a@mail.com</email>
<lname></lname>
<fname></fname>
<birthday>
<year>2000</year>
<month>JANUARY</month>
<chronology>
<id>ISO</id>
<calendarType>iso8601</calendarType>
</chronology>
<dayOfMonth>1</dayOfMonth>
<dayOfWeek>SATURDAY</dayOfWeek>
<era>CE</era>
<dayOfYear>1</dayOfYear>
<leapYear>true</leapYear>
<monthValue>1</monthValue>
</birthday>
</user>
我想要的是(特别是 birthDay 标签):
<user>
<email>a@mail.com</email>
<lname></lname>
<fname></fname>
<birthday>2000-01-01</birthday>
</user>
代码如下:
dto 类:
import org.springframework.format.annotation.DateTimeFormat
import java.time.LocalDate
@JacksonXmlRootElement
data class User (var email: String? = "",
var lname: String = "",
var fname: String = "",
@DateTimeFormat(pattern = "yyyy-MM-dd")
var birthday: LocalDate? = null)
控制器类:
@RestController
@RequestMapping("/")
class Controller {
@PostMapping("/post")
fun registerByMail(@Valid body: User) : ResponseEntity<Any> {
.
.
.
var user = User(birthDay = body.birthDay)
return ResponseEntity.ok(user)
请让我知道我哪里做错了。我正在使用邮递员发出 POST 请求。
编辑:我也尝试过这里提到的解决方案:JSON Java 8 LocalDateTime format in Spring Boot,但这对我也不起作用。
当我使用 com.fasterxml.jackson.annotation.JsonFormat 注释和所需依赖项时,出现以下错误:
<defaultMessage>Failed to convert value of type 'java.lang.String[]' to
required type 'java.time.LocalDate'; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type [java.lang.String] to type
[@com.fasterxml.jackson.annotation.JsonFormat java.time.LocalDate] for value
'2000-01-01'; nested exception is java.lang.IllegalArgumentException: Parse
attempt failed for value [2000-01-01]</defaultMessage>
【问题讨论】:
-
我尝试了这个解决方案,但出现错误。上面编辑的内容。谢谢。
标签: rest spring-boot kotlin