【问题标题】:Custom deserialization of path variable in spring web starterspring web starter中路径变量的自定义反序列化
【发布时间】:2018-06-14 16:56:33
【问题描述】:

在 Spring Web 响应式中为路径变量注册自定义反序列化器的正确方法是什么?

例子:

@GetMapping("test/{customType}")
public String test(@PathVariable CustomType customType) { ...

我尝试了 ObjectMapperBuilder、ObjectMapper 和直接通过 @JsonDeserialize(using = CustomTypeMapper.class) 但它不会注册:

Response status 500 with reason "Conversion not supported."; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type '...CustomType'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type '...CustomType': no matching editors or conversion strategy found

【问题讨论】:

标签: java spring-webflux reactive


【解决方案1】:

路径变量反序列化不需要jackson,可以使用org.springframework.core.convert.converter.Converter

例如:

@Component
public class StringToLocalDateTimeConverter
  implements Converter<String, LocalDateTime> {

    @Override
    public LocalDateTime convert(String source) {
        return LocalDateTime.parse(
          source, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }
}

@GetMapping("/findbydate/{date}")
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
    return ...;
}

Here's an article 示例

【讨论】:

    【解决方案2】:

    我最终使用了@ModelValue,因为它在语义上不是反序列化,只是解析一个键。

    @RestController
    public class FooController {
    
       @GetMapping("test/{customType}")
       public String test(@ModelAttribute CustomType customType) { ... }
    }
    
    @ControllerAdvice
    public class GlobalControllerAdvice {
    
       @ModelAttribute("customType")
       public CustomType getCustomType(@PathVariable String customType) {
          CustomeType result = // map value to object
          return result;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-25
      • 2013-11-20
      • 2018-02-19
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 2019-05-07
      相关资源
      最近更新 更多