gpt4 book ai didi

java - 如何在 Rest 请求体内使用带有单字符序列构造函数/工厂方法的对象而不是单字符串构造函数?

转载 作者:行者123 更新时间:2023-12-01 09:46:15 25 4
gpt4 key购买 nike

我有一个带有方法的 Controller :

@RequestMapping(value = "/request", method = RequestMethod.POST)
public Response<Boolean> requestAppt(
@RequestBody @Valid ApptRequest request
) {
System.out.println(request);
return Response.success(true);
}

我的 ApptRequest 是:

import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.time.OffsetDateTime;

public class ApptRequest implements Serializable{

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private OffsetDateTime date;

public ApptRequest() {
}

public OffsetDateTime getDate() {
return date;
}

public void setDate(OffsetDateTime date) {
this.date = date;
}
}

当我尝试发送带有请求正文的请求时:

{
"date": "2016-05-11T13:30:38+02:00"
}

我有一个异常(exception):

org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not instantiate value of type [simple type, class java.time.OffsetDateTime] from String value ('2016-05-11T13:30:38+02:00'); no single-String constructor/factory method

它表示OffsetDateTime 应该有一个只有一个字符串参数的构造函数或工厂方法。但我发现它需要带有 CharSequence 参数的工厂方法:

/**
* Obtains an instance of {@code OffsetDateTime} from a text string
* such as {@code 2007-12-03T10:15:30+01:00}.
* <p>
* The string must represent a valid date-time and is parsed using
* {@link java.time.format.DateTimeFormatter#ISO_OFFSET_DATE_TIME}.
*
* @param text the text to parse such as "2007-12-03T10:15:30+01:00", not null
* @return the parsed offset date-time, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static OffsetDateTime parse(CharSequence text) {
return parse(text, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}

如果我尝试使用日期作为请求参数而不是请求正文属性,一切都会正常工作:

@RequestMapping(value = "/request", method = RequestMethod.POST)
public Response<Boolean> requestAppt(
@RequestParam @Valid @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime date
) {
System.out.println(date);
return Response.success(true);
}

也许我应该使用一些注释或类似的东西手动指定适当的构造函数?

最佳答案

将 datatype:jackson-datatype-jsr310 添加到类路径应该会有所帮助。灵感来自JSON Java 8 LocalDateTime format in Spring Boot

关于java - 如何在 Rest 请求体内使用带有单字符序列构造函数/工厂方法的对象而不是单字符串构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37993532/

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