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

标签 java json spring rest spring-boot

我有一个带有方法的 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/

相关文章:

用于 GAE 的 Java 与 Python

java - LibGDX Scene2D 对多点触控的表现很奇怪

java - 通过REST中的RestTemplate进行POST请求

java - Google App Engine 上 Spring Boot 应用程序的 Maven 配置文件

java - 如何清除要进行垃圾收集的对象(HashMap)-Java

javascript - 正则表达式排除具有奇怪 URL 的链接

java - 使用 Map 对 Java 对象进行 jackson 序列化?

json - 使用 double 作为数据类型构造 Json 值

spring - 防止 Spring 中某些 bean 按类型 Autowiring

java - 根据编辑请求中的用户角色选择要使用的 pojo