我在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>
答案 0 :(得分:0)
您必须注释字段@field:JsonSerialize
而不是属性。
除此之外,您还必须使用@JsonFormat
@JacksonXmlRootElement
data class User(
var email: String? = "",
var lname: String = "",
var fname: String = "",
@field:JsonFormat(pattern = "yyyy-MM-dd")
@field:JsonSerialize(using = LocalDateSerializer::class)
@field:JsonDeserialize(using = LocalDateDeserializer::class)
var birthday: LocalDate? = null
)
我的小测试:
val mapper = XmlMapper()
val xml = mapper.writeValueAsString(User(birthday = LocalDate.now()))
println(xml)
生成以下输出:
<User><email></email><lname></lname><fname></fname><birthday>2018-10-19</birthday></User>