As mentioned here: https://github.com/spring-projects/spring-framework/issues/27697#issuecomment-2135164974
Since migrating from Spring Boot 2.7.x to 3.3.x the jackson ObjectMapper is not able to serialize org.springframework.http.HttpMethod
anymore. You have to write now your own modules with serializer and deserializer now.
public class JacksonConfig{
@Bean
SimpleModule httpMethodModule() {
SimpleModule module = new SimpleModule();
module.addSerializer(HttpMethod.class, new HttpMethodSerializer());
module.addDeserializer(HttpMethod.class, new HttpMethodDeserializer());
return module;
}
@Bean
Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> builder
.modules(httpMethodModule());
}
}
public class HttpMethodSerializer extends JsonSerializer<HttpMethod> {
@Override
public void serialize(HttpMethod httpMethod, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
jsonGenerator.writeString(httpMethod.name());
}
}
public class HttpMethodDeserializer extends JsonDeserializer<HttpMethod> {
@Override
public HttpMethod deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
return HttpMethod.valueOf(jsonParser.getText().toUpperCase());
}
}
Comment From: lucky8987
@mwcodeslave Can adding public String getName() {
return this.name;
}
to HttpMethod solve your problem? But this will lead to another issue, the serialization of GET objects will be {"name":"GET"} instead of "GET". I'm not sure if this is what you want.
Comment From: bclozel
@lucky8987 thanks for helping out! Indeed, it' looks like we cannot make this class "Jackson-friendly" and have a similar serialization format without breaking the current API.
@mwcodeslave I think the serializer implementations you've shared look like the expected solution. Framework provides many classes in the org.springframework.http
package and none of them are expected to be used to write/read JSON payloads. I don't think we're advising developers to use such classes as part of their payloads. I'm not seeing an easy way out for this; we could add Jackson-specific annotations or implementations but we would need to do so for entire packages to be consistent. Sharing serializer implementations like the one suggested above also feel outside of the scope of this project.
I'm closing this issue for now; developers should use your implementations if they wish to retain the serialization behavior as it was. Thanks!
Comment From: lucky8987
@bclozel I agree with your suggestion, and if necessary, I can add this custom HttpMethodSerializer to the unit test, which can provide reference for those who encounter the same problem.