【问题标题】:How to send time value from Postman to my REST api如何将时间值从邮递员发送到我的 REST api
【发布时间】:2016-06-25 01:54:33
【问题描述】:

我有一个类有一个日期类型的变量,代表一个时间

@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 方法,以及何时发送

{ “产品名称”:“名称”, “日期”:“2016-03-10”, “时间”:“10:29” }

我明白了

400 错误请求

带有描述:

客户端发送的请求语法错误。

当我没有时间尝试时,它就过去了。

【问题讨论】:

    标签: spring rest datetime postman


    【解决方案1】:

    改一下

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

    而不是

    @NotNull()
    private String time;
    

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

    【讨论】:

      【解决方案2】:

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

      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 文档。

      【讨论】:

      • 现在可以使用了。是的,我想要 HH:mm。非常感谢!但现在我有另一个问题:) 当我发布“时间”:“10:29”时,它会将其处理为 11:29。你知道为什么会这样吗?
      • @TamaraB 这可能是时区问题。我认为您在反序列化日期/时间时需要考虑时区,并使用 UTC 时区将日期存储在数据库中。只需避免在本地时间存储日期(当然,除非您在 UTC 时区)。
      猜你喜欢
      • 2018-11-01
      • 1970-01-01
      • 2022-01-25
      • 2015-03-21
      • 2015-11-11
      • 1970-01-01
      • 2018-12-01
      • 2019-01-09
      • 2022-01-25
      相关资源
      最近更新 更多