I graphql-spqr,java.util.Date被定义为标量。是否可以覆盖java.util.Date的序列化/反序列化,以获得日期的不同字符串表示?
此answer中提到的ScalarStrategy已从最新版本中删除。
public class Order {
private String id;
private Date orderDate; //GraphQLScalarType "Date"
public Order() {
}
public Order(String id, String bookId, Date orderDate) {
this.id = id;
this.orderDate = orderDate;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
}GraphQL响应:
{
"data": {
"createOrder": {
"id": "74e4816c-f850-4d63-9855-e4601fa125f4",
"orderDate": "2019-05-26T08:25:01.349Z", // --> 2019-05-26
}
}
}发布于 2019-08-07 18:02:00
ScalarStrategy不是实现你想要的东西的正确方式。当您想要更改Java类型映射到GraphQL的方式时,通常需要提供一个新的(或自定义现有的) TypeMapper。
看看现有的Date标量实现,并以类似的方式实现您自己的实现。然后实现一个自定义TypeMapper,它总是从toGraphQLType和toGraphQLInputType方法返回该标量的静态实例。
public class CustomTypeMapper implements TypeMapper {
private static final GraphQLScalarType GraphQLCustomDate = ...;
@Override
public GraphQLOutputType toGraphQLType(...) {
return GraphQLCustomDate;
}
@Override
public GraphQLInputType toGraphQLInputType(...) {
return GraphQLCustomDate;
}
@Override
public boolean supports(AnnotatedType type) {
return type.getType() == Date.class; // This mapper only deals with Date
}
}要注册它,请调用generator.withTypeMappers(new CustomTypeMapper()。
也就是说,因为您只想减少时间部分,所以在这里您最好使用LocalDate。您可以通过注册一个TypeAdapter (它只是一个映射器+转换器)让SPQR透明地做到这一点,但在您的情况下,使用上面解释的简单映射器是一种更有效的解决方案。如果您仍然决定采用适配器的方式,则可以继承AbstractTypeAdapter<Date, LocalDate>并实现转换逻辑(应该很简单)。通过generator.withTypeAdapters注册,或将其注册为映射器和转换器。
https://stackoverflow.com/questions/56311700
复制相似问题