Reputation: 95
I have a class with a variable of type Date, representing a time
@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;
....
}
Now I'm trying CRUD methods on Postman, and when I send
{ "productName": "name", "date": "2016-03-10", "time": "10:29" }
I get
400 Bad Request
with a description:
The request sent by the client was syntactically incorrect.
When I try without time, it passes.
Upvotes: 3
Views: 31966
Reputation: 130927
If you are using Jackson, you can try the following solutions:
JsonDeserializer
Define a custom 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);
}
}
}
Then just annotate your time
attribute with @JsonDeserialize
:
@NotNull
@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "hh:mm")
@JsonDeserialize(using = TimeDeserializer.class)
private Date time;
@JsonFormat
annotationAlternativelly, you could try the @JsonFormat
annotation, instead of creating a custom JsonDeserializer
:
@NotNull
@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "hh:mm")
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="hh:mm")
private Date time;
Is hh:mm
the format you really want?
hh
means hours in 1-12 format while HH
means hours in 0-23 format. If you go for the 1-12 format, you could consider using the AM/PM marker: hh:mm a
.
For more details, have a look at the SimpleDateFormat
documentation.
Upvotes: 1
Reputation: 1185
change this
@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "hh:mm")
@NotNull()
private Date time;
instead of
@NotNull()
private String time;
because you try parse to String value 10:29
not a valid representation for your time
variable
Upvotes: 0