处理请求body中传递的simpledateformat

发布于 2025-01-22 18:08:36 字数 1009 浏览 2 评论 0原文

我正在开发一个简单的休息控制器。我在请求主体中收到一个简单的对象。看起来像这样:

2014-04-13T03:42:06-02:00

我当前的方法现在是:

@PostMapping
        public ResponseEntity<Flight> addFlight(@RequestBody JSONObject object) {
            Flight newFlight = new Flight(object.get("flightNumber").toString(), new 
            SimpleDateFormat ( object.get("departureDate").toString()));
            repository.save(newFlight);
            return ResponseEntity.status(HttpStatus.ACCEPTED).body(newFlight);
        }

班级

@Data
@Entity
@DynamicUpdate
@NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
@RequiredArgsConstructor
@AllArgsConstructor
public class Flight {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private final String flightNumber;
    private final SimpleDateFormat date;
}

所有内容都很好,但是当我发送帖子或获取时,我会收到我传递的所有数据,但是SimpleDateFormat是无效的。我该如何维修? 我还尝试将对象传递给FlightClass,然后在班级的构造函数中使用转换器,但我仍然有空。

I'm developing a simple REST Controller. I'm receiving a SimpleDateFormat object in Request body. Looks like that:

2014-04-13T03:42:06-02:00

My current method now is:

@PostMapping
        public ResponseEntity<Flight> addFlight(@RequestBody JSONObject object) {
            Flight newFlight = new Flight(object.get("flightNumber").toString(), new 
            SimpleDateFormat ( object.get("departureDate").toString()));
            repository.save(newFlight);
            return ResponseEntity.status(HttpStatus.ACCEPTED).body(newFlight);
        }

And class

@Data
@Entity
@DynamicUpdate
@NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
@RequiredArgsConstructor
@AllArgsConstructor
public class Flight {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private final String flightNumber;
    private final SimpleDateFormat date;
}

Everything is compiling fine, but when I'm sending POST or GET I receive all of the data that I've passed, but SimpleDateFormat is null. How could I repair it?
I've also tried to pass Object to FlightClass and then use a converter in the class's constructor, but I've still had null.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

成熟稳重的好男人 2025-01-29 18:08:36

simpledateateFormat 推荐 offsetDateTime 以来您的输入代表ISO-- 8601带偏移

ISO-8601日历系统中UTC/Greenwich偏移的日期时间,例如2007-12-03T10:15:30+01:00。

OffsetDateTime dateTime = OffsetDateTime.parse(object.get("departureDate").toString());

SimpleDateFormat is a legacy class and i would recommend OffsetDateTime since your input represents ISO-8601 with offset

A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.

OffsetDateTime dateTime = OffsetDateTime.parse(object.get("departureDate").toString());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文