简体   繁体   中英

How to send time value from Postman to my REST api

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.

If you are using Jackson, you can try the following solutions:

1. Using a custom 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;

2. Using the @JsonFormat annotation

Alternativelly, 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;

One last thing

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM