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.
CodePudding user response:
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());