Spring @ModelAttribute模型字段映射 [英] Spring @ModelAttribute Model field mapping

查看:327
本文介绍了Spring @ModelAttribute模型字段映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重写用内部框架编写的旧REST服务,以使用Spring.我有一个带有POST方法的Controller,该方法采用一个参数作为POST或x-www-form-urlencoded主体.在回答了多个StackOverflow答案之后,我使用了@ModelAttribute批注并创建了一个模型.

I am rewriting an old REST service written in an in-house framework to use Spring. I have a Controller with a POST method which takes a parameter either as a POST or as x-www-form-urlencoded body. Following multiple StackOverflow answers, I used @ModelAttribute annotation and created a model.

我的问题是旧的REST API在蛇形情况下使用属性名称-说some_property.我希望我的Java代码遵循Java命名约定,因此在我的模型中,该字段称为someProperty.我尝试像在DTO对象中一样使用@JsonProperty批注,但这一次这不起作用.只有在模型中的字段命名为some_property的情况下,我才设法使代码正常工作.这是我的示例代码:

My problem is that the old REST API is using a property name in snake case - say some_property. I want my Java code to follow the Java naming conventions so in my model the field is called someProperty. I tried using the @JsonProperty annotation as I do in my DTO objects but this time this didn't work. I only managed to make the code work if the field in the model was named some_property. Here is my example code:

import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/my/api/root")
public class SomethingController {

    @PostMapping("/my/api/suffix")
    public Mono<Object> getSomething(
            @RequestParam(name = "some_property", required = false) String someProperty,
            @ModelAttribute("some_property") Model somePropertyModel) {
        // calling my service here
    }

    public class Model {
        @JsonProperty("some_property")
        private String someProperty;

        private String some_property;
        // Getters and setters here
    }
}

我正在寻找注释或任何其他优雅的方式来将Java命名样式保留在代码中,但使用REST API中的旧属性名称.

I am searching for annotation or any other elegant way to keep the Java naming style in the code but use the legacy property name from the REST API.

推荐答案

@JsonProperty批注只能使用JSON格式,但是您正在使用x-www-form-urlencoded.

The @JsonProperty annotation can only work with the JSON format, but you're using x-www-form-urlencoded.

如果您无法更改POST类型,则必须编写自己的Jackson ObjectMapper:

If you can't change your POST type, you have to write your own Jackson ObjectMapper:

@JsonProperty不适用于Content-类型:application/x-www-form-urlencoded

这篇关于Spring @ModelAttribute模型字段映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆