我正在尝试传递一个新的日历事件以将新事件添加到日历中。我通过以下 JSON...
{
"summary": "My Event",
"location": "201 w. 1st Ave Columbus, OH 43201",
"description": "This is my first test event to the calendar",
"start":{
"dateTime": "2023-05-01T09:00:00-07:00",
"timeZone": "America/Los_Angeles"
},
"end":{
"dateTime": "2023-05-02T09:00:00-07:00",
"timeZone": "America/Los_Angeles"
}
}
然后我尝试编写一个控制器来接受
com.google.api.services.calendar.model.Event
...
@PostMapping(path = Array("/calendar/event"))
def addEvent(@RequestBody event: Event): Unit = {
...
}
但是当我跑步时我得到
{
"timestamp": "2023-04-30T14:49:41.718+00:00",
"status": 400,
"error": "Bad Request",
"path": "/google/calendar/event"
}
我认为有一种方法可以使用
@JsonComponent
和单独的 case class
但我无法让它工作。有没有办法可以将com.google.api.services.calendar.model.Event
作为请求主体传递?如果不是,我将如何使用 @JsonComponent
做类似的事情,或者有更清洁的方法吗?我宁愿将额外的部门保持在最低限度。
看起来 Jackson 无法将
start
和 end
字段反序列化为 com.google.api.services.calendar.model.EventDateTime
对象。您可以将其作为自定义对象接受,然后将其转换为 Google 事件,而不是在控制器中将请求主体作为 com.google.api.services.calendar.model.Event
接受。自定义类(在 Java 中)可能如下所示:
import java.time.ZonedDateTime;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventDateTime;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class InputEvent {
private String summary;
private String location;
private String description;
private EventDateAndTimeZone start;
private EventDateAndTimeZone end;
@Getter
@Setter
public static class EventDateAndTimeZone {
private ZonedDateTime dateTime;
private String timeZone;
}
public Event toCalendarEvent() {
Event calendarEvent = new Event();
calendarEvent.setSummary(summary);
calendarEvent.setLocation(location);
calendarEvent.setDescription(description);
EventDateTime startDateTime = new EventDateTime();
startDateTime.setDateTime(new DateTime(start.dateTime.toEpochSecond() * 1000));
startDateTime.setTimeZone(start.timeZone);
calendarEvent.setStart(startDateTime);
EventDateTime endDateTime = new EventDateTime();
endDateTime.setDateTime(new DateTime(end.dateTime.toEpochSecond() * 1000));
endDateTime.setTimeZone(end.timeZone);
calendarEvent.setEnd(endDateTime);
return calendarEvent;
}
}
自定义类中的
toCalendarEvent()
方法会将自定义对象转换为Google Event 对象。您可以在控制器中调用此方法,然后根据需要处理 Google Event 对象。
@PostMapping("/calendar/event")
public void addEvent(@RequestBody InputEvent event) {
Event googleCalendarEvent = event.toCalendarEvent();
LOGGER.info("Transformed event: {}", googleCalendarEvent.toString());
// Process googleCalendarEvent
}