java 将@RequestBody 转换为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5889973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:18:06  来源:igfitidea点击:

Converting @RequestBody to an object

javajqueryspringjakarta-eespring-mvc

提问by Firdous Amir

Guys, Well I have done enough research still I can't find the solution to this.

伙计们,我已经做了足够的研究,但仍然找不到解决方案。

In a nutshell, I'm simply passing url encoded form data to the Controller method and trying to convert it as a domain object which has Date and integers.

简而言之,我只是将 url 编码的表单数据传递给 Controller 方法,并尝试将其转换为具有日期和整数的域对象。

@RequestMapping(value = "/savePassport", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse savePassport(@RequestBody StaffPassport passport, HttpServletResponse response) {

    // Some operations.

}

}

The Staff Passport looks like this:

员工护照看起来像这样:

import java.sql.Date;

public class StaffPassport {

    private int staffId;
    private String passportNumber;
    private String placeOfIssue;
    private Date issueDate;
    private Date expiryDate;
    private String spouseName;
    private String oldPassportRef;
    private String visaInfo;
    private String description;
//gets/sets
}

When I invoke the /savePassport, I get unsupported media exception. I guess it's related to casting.

当我调用 /savePassport 时,我得到不受支持的媒体异常。我想这与铸造有关。

I can't this working right. Of course I can catch individual form data using @RequestParam and manually do the casting but that's not the point of a framework isn't it?

我不能正常工作。当然,我可以使用 @RequestParam 捕获单个表单数据并手动进行转换,但这不是框架的重点,不是吗?

Where am I going wrong? And you are right. I'm a beginner in Spring, but I love it.

我哪里错了?你是对的。我是 Spring 的初学者,但我喜欢它。

回答by Affe

Looks like you're using the wrong annotation. @RequestBodyis for taking a request that has arbitrary content in its body,such as JSON, some application defined XML, comma separated variables.. whatever. And using a marshaller that you configure in the dispatcher servlet to turn it into objects.

看起来您使用了错误的注释。 @RequestBody用于接收在其正文中具有任意内容的请求,例如 JSON、某些应用程序定义的 XML、逗号分隔的变量……无论如何。并使用您在调度程序 servlet 中配置的编组器将其转换为对象。

If all you want to do is ask Spring to bind a plain old form post onto the backing object for you, the correct annotation to put on the method parameter is @ModelAttribute.

如果您只想让 Spring 为您绑定一个普通的旧表单帖子到支持对象上,那么放置在方法参数上的正确注释是@ModelAttribute.

回答by Flyhard

If you are posting a JSON Object with jQuery and you want Spring to be able to process it with @RequestBody, use JSON.stringify(....) in your data. Here an example:

如果您使用 jQuery 发布 JSON 对象,并且希望 Spring 能够使用 @RequestBody 处理它,请在您的数据中使用 JSON.stringify(....)。这里有一个例子:

var data = { "id": 3, "name": "test" }
$.post("processJsonData.html",JSON.stringify(data), function(data){
    ...
  }
);

If you don't use the JSON.stringify() then you will submit the data as form data and Spring will tell you that you have an unsupported media type.

如果您不使用 JSON.stringify() ,那么您将数据作为表单数据提交,Spring 会告诉您您有一个不受支持的媒体类型。

回答by danny.lesnik

First of all be sure that you have

首先要确保你有

<mvc:annotation-driven /> 

in your Spring configuration file. This is mandatory for working with JSOn in SPring MVC.

在您的 Spring 配置文件中。这对于在 SPring MVC 中使用 JSOn 是强制性的。

Second, I recommend you to test wether request to the server has application/json content type. I belive Fiddler2 will help you to do so.

其次,我建议您测试对服务器的请求是否具有 application/json 内容类型。我相信 Fiddler2 会帮助你做到这一点。

Third, but I'm not sure about it, Try to change Date items in your POJO from SQL type to regular java type.

第三,但我不确定,尝试将 POJO 中的日期项从 SQL 类型更改为常规 Java 类型。

UPDATE: just looked at the Form and it seems like your "Accept" HTTP Header should be also application/json. Please test this issue with Fiddler2 as well.

更新:刚刚查看了表单,似乎您的“接受”HTTP 标头也应该是 application/json。请也用 Fiddler2 测试这个问题。

回答by David

I assume that you are posting JSON and want Spring to convert to StaffPassport. If you are getting an Unsupported media exception, it is because Spring could not figure out an appropriate way to perform the conversion.

我假设您正在发布 JSON 并希望 Spring 转换为 StaffPassport。如果您收到 Unsupported media 异常,那是因为 Spring 无法找到执行转换的合适方法。

For Spring to convert JSON, it needs Hymanson -- make sure you have the Hymanson jars in your project. If this is a Maven based project you can add the Hymanson-mapper-asl artifact ID to your pom.xml. This should give you the Hymanson-mapper and Hymanson-core jars.

为了让 Spring 转换 JSON,它需要 Hymanson —— 确保你的项目中有 Hymanson jars。如果这是一个基于 Maven 的项目,您可以将 Hymanson-mapper-asl 工件 ID 添加到您的 pom.xml。这应该给你 Hymanson-mapper 和 Hymanson-core jars。

Edit: I should mention that this applies to Spring 3 (I recently ran into this problem). I'm not sure what else is required for previous versions of Spring.

编辑:我应该提到这适用于 Spring 3(我最近遇到了这个问题)。我不确定以前版本的 Spring 还需要什么。

回答by Bobby Fisher

Check into HttpMessageConverter interface and its implementations. You could write your own implementation of it to convert it to the domain model you want. By the time the control gets to your method, you can access it as if your domain model object is passed.

检查 HttpMessageConverter 接口及其实现。您可以编写自己的实现来将其转换为您想要的域模型。当控件到达您的方法时,您可以访问它,就像您的域模型对象被传递一样。

回答by Bobby Fisher

Ok, I think I should refine my answer. I do not have direct experience of using it in a spring-mvc project but spring-integration. I am pretty sure the applicable media type (application/x-url-form-encoded) is already handled and converted to MultiMap by Spring framework; so, retrieve the values from that just like any other map with the key value being your form variable and populate your business model.

好的,我想我应该完善我的答案。我没有在 spring-mvc 项目中使用它的直接经验,而是在 spring-integration 中使用它。我很确定适用的媒体类型(application/x-url-form-encoded)已经被 Spring 框架处理并转换为 MultiMap;因此,就像任何其他地图一样,从中检索值,键值为您的表单变量并填充您的业务模型。

HTH.

哈。