![](/img/trans.png)
[英]how to catch a file on the rest api controller and what method to send it with Postman
[英]How to send time value from Postman to my REST api
我有一个带有 Date 类型变量的类,表示时间
@Entity
public class Product implements Serializable {
private static final long serialVersionUID = -7181205262894478929L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int productId;
@NotNull()
private String productName;
@Temporal(TemporalType.DATE)
@DateTimeFormat(style = "yyyy-MM-dd")
@NotNull()
private Date date;
@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "hh:mm")
@NotNull()
private Date time;
....
}
现在我正在 Postman 上尝试 CRUD 方法,当我发送
{ "productName": "name", "date": "2016-03-10", "time": "10:29" }
我得到
400 错误请求
附有说明:
客户端发送的请求在语法上不正确。
当我没有时间尝试时,它就过去了。
如果您使用的是 Jackson,您可以尝试以下解决方案:
JsonDeserializer
定义一个自定义JsonDeserializer
:
public class TimeDeserializer extends JsonDeserializer<Date> {
private SimpleDateFormat format = new SimpleDateFormat("hh:mm");
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
String date = p.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
然后只需使用@JsonDeserialize
注释您的time
属性:
@NotNull
@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "hh:mm")
@JsonDeserialize(using = TimeDeserializer.class)
private Date time;
@JsonFormat
注解或者,您可以尝试使用@JsonFormat
注释,而不是创建自定义JsonDeserializer
:
@NotNull
@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "hh:mm")
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="hh:mm")
private Date time;
hh:mm
是您真正想要的格式吗?
hh
表示1-12 格式的小时数,而HH
表示0-23 格式的小时数。 如果您选择 1-12 格式,您可以考虑使用AM/PM 标记: hh:mm a
。
有关更多详细信息,请查看SimpleDateFormat
文档。
改变这个
@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "hh:mm")
@NotNull()
private Date time;
代替
@NotNull()
private String time;
因为您尝试解析为字符串值10:29
不是您的time
变量的有效表示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.