如何从Postman发送时间值到我的REST api

时间:2016-03-10 09:44:59

标签: spring rest datetime postman

我有一个类,其类型为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",           "时间":" 10:29"       }

我收到400 Bad Request with description:客户端发送的请求在语法上是不正确的。 当我没有时间尝试时,它就过去了。

2 个答案:

答案 0 :(得分:1)

如果您使用的是杰克逊,可以尝试以下解决方案:

1。使用自定义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;

2。使用@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文档。

答案 1 :(得分:0)

更改此

@Temporal(TemporalType.TIME)
@DateTimeFormat(style = "hh:mm")
@NotNull()
private Date time;

而不是

@NotNull()
private String time;

因为您尝试解析字符串值10:29而不是time变量的有效表示