弹簧卷筒启动器中路径变量的自定义反序列化

时间:2018-06-14 16:56:34

标签: java spring-webflux reactive

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

示例:

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

我尝试了ObjectMapperBuilder,ObjectMapper并直接通过@JsonDeserialize(使用= 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

2 个答案:

答案 0 :(得分:1)

对于路径变量反序列化,您不需要涉及杰克逊,可以使用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和示例

答案 1 :(得分:0)

我最终使用了@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;
   }
}