GraphQL自定义标量(LocalDateTime)不适用于Java中的JSON输入

时间:2018-07-30 12:21:36

标签: java spring-boot graphql graphql-java

在我们的GraphQL SpringBoot应用程序中,我们已成功通过graphql-java-datetime

LocalDateTime 使用自定义标量实现
<dependency>
   <groupId>com.zhokhov.graphql</groupId>
   <artifactId>graphql-datetime-spring-boot-starter</artifactId>
   <version>1.2.0</version>
</dependency>
<dependency>
   <groupId>com.graphql-java</groupId>
   <artifactId>graphql-spring-boot-starter</artifactId>
   <version>4.0.0</version>
</dependency>
<dependency>
   <groupId>com.graphql-java</groupId>
   <artifactId>graphql-java-tools</artifactId>
   <version>4.3.0</version>
</dependency>

只要我们仅在架构中将其用作字符串,它就可以正常工作

scalar LocalDateTime

input AttendanceFilter {
    # date format yyyy-MM-ddThh:mm:ss
    fromDateTime: String
    toDateTime: String
}

type Query {
    attendanceList(filter: AttendanceFilter): [Attendance]
} 

type Attendance {
    date: LocalDateTime
}

我们还可以在Java解析器实现中使用Java类型的LocalDateTime

public List<AttendancePOJO> attendanceList(AttendanceFilter filter) {
    LocalDateTime fromDateTime = filter.getFromDateTime;
    LocalDateTime toDateTime = filter.getToDateTime;
    return jpaAttendanceRepository.findByFromTimeAfterAndToTimeBefore(fromDateTime, toDateTime) }

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

public class AttendanceFilter {
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonFormat(pattern = "yyyy[-]MM[-]dd'T'HH[:]mm[:]ss")
    private LocalDateTime fromDateTime;

    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonFormat(pattern = "yyyy[-]MM[-]dd'T'HH[:]mm[:]ss")
    private LocalDateTime toDateTime;
}

和GraphQL查询,例如

query: {
  attendanceList(filter: {fromDateTime: "2018-01-01T00:00:00", 
    toDateTime: "2018-06-01T23:59:59"}) { date }
}

工作正常。

但是,当我们想使其更具可读性时,即使在架构查询中也可以使用固定格式的 String 参数使用 LocalDateTime 来代替它。 >

input AttendanceFilter {
    # date format yyyy-MM-ddThh:mm:ss
    fromDateTime: LocalDateTime
    toDateTime: LocalDateTime
}

反序列化似乎无法正常工作并返回错误

Exception while fetching data (/attendanceList) : Unexpected token (START_OBJECT), expected VALUE_STRING: Expected array or string. at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: ***.AttendanceFilter["fromDateTime"])
java.lang.IllegalArgumentException: Unexpected token (START_OBJECT), expected VALUE_STRING: Expected array or string. at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: ***.AttendanceFilter["fromDateTime"])

有人可以建议如何将AttendanceFilter对象中的JSON输入值转换为Java吗?预先非常感谢

0 个答案:

没有答案