转换器适用于 RequestParameter 但不适用于 RequestBody 字段

Converter works for RequestParameter but not for RequestBody field

我有以下转换器:

@Component
public class CountryEnumConverter implements Converter<String, CountryEnum> {

    @Override
    public CountryEnum convert(String country) {
        CountryEnum countryEnum = CountryEnum.getBySign(country);

        if (countryEnum == null) {
            throw new IllegalArgumentException(country + " - Country is not supported!");
        }

        return countryEnum;
    }
}

注册为RequestParam时调用

@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestParam CountryEnum country) {
    ....
}

但是当用于 RequstBody 中的字段时永远不会调用此转换器:

@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestBody MyBody myBody) {
    ....
}

public class MyBody {

    @NotNull
    private CountryEnum country;


    public MyBody() {
    }

    public CountryEnum getCountry() {
        return country;
    }

    public void setCountry(CountryEnum country) {
        this.country = country;
    }

}

您现有的 org.springframework.core.convert.converter.Converter 实例仅适用于作为表单编码数据提交的数据。使用 @RequestBody,您将发送 JSON 数据,这些数据将使用 Jackson 库进行反序列化。

然后您可以创建 com.fasterxml.jackson.databind.util.StdConverter<IN, OUT>

的实例
public class StringToCountryTypeConverter extends StdConverter<String, CountryType> {

  @Override
  public CountryType convert(String value) {
      //convert and return
  }
}

然后将其应用于目标 属性:

public class MyBody {

    @NotNull
    @JsonDeserialize(converter = StringToCountryTypeConverter.class)
    private CountryEnum country;
}

鉴于这 2 个接口的相似性,我希望您可以创建一个 class 来处理这两种情况:

public class StringToCountryTypeConverter extends StdConverter<String, CountryType> 
           implements org.springframework.core.convert.converter.Converter<String, CountryType> {
  @Override
  public CountryType convert(String value) {
      //convert and return
  }
}

我发现如果我将以下代码添加到我的 CountryEnum 中就可以了。

@JsonCreator
public static CountryEnum fromString(String value) {
    CountryEnumConverter converter = new CountryEnumConverter();
    return converter.convert(value);
}