java 如何将 JSON 对象映射到 Spring 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11021417/
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-31 03:28:31  来源:igfitidea点击:

How to map JSON object to Spring Object

javajsonspringspring-mvc

提问by SJS

How to map JSON object to Spring Object... I have AJAX, posting a JSON object to my Spring Controller but how do I make Spring turn that JSON into a Object in java

如何将 JSON 对象映射到 Spring 对象...我有 AJAX,将 JSON 对象发布到我的 Spring 控制器,但如何让 Spring 将该 JSON 转换为 Java 中的对象

Java Code:

Java代码:

@RequestMapping(method=RequestMethod.POST, value="/employee")
    public ModelAndView addEmployee(@RequestBody String body) {

        System.out.println("in post: " + body);
        Source source = new StreamSource(new StringReader(body));


        System.out.println("source: " + source.toString());
        //
        // how do I turn the JSON String into a Java Object?
        //
        return new ModelAndView(XML_VIEW_NAME, "object", body);
    }

JavaSript/html code:

JavaSript/html 代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>This is a project to show how to use RESTful</title>
</head>
<body>
<script type="text/javascript">var contexPath = "<%=request.getContextPath()%>";</script>
<script src="<%=request.getContextPath()%>/js/jquery.js"></script>


<script type="text/javascript">
function doAjaxPost() {  


    var queryString = $('#htmlform').serialize();

    alert("doAjaxPost Called :" + queryString +":");

       $.ajax({
            contentType : "application/json",
            dataType : 'json',
            type : "POST",
            url : contexPath + "/service/employee",
            data : queryString, //json serialization (like array.serializeArray() etc)

            success : function(data) {
                alert("Thanks for submitting.  \n\n" + response.result);
               // response
            },
            error : function(request, status, error) {
                   alert('Error: ' + e); 
            }
        });
    }  
</script>

<H1>Add Employee</H1>

<p>
<form name="htmlform" id="htmlform">
<table border=1>
    <thead><tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
    </tr></thead>

    <tr>
        <td><input  type="text" name="ID" maxlength="5" size="3"></td>
        <td><input  type="text" name="Name" maxlength="10" size="10"></td>
        <td><input  type="text" name="Email" maxlength="10" size="10"></td>
    </tr>

</table>
<input type="button" value="Save Employee" onclick="doAjaxPost();" />
<p>
<p>
</form>
[<a href="http://localhost:8080/RESTful/service/employees">List all Employees</a> | <a href="add.jsp">Employee Form Test</a>]


</body>
</html>

回答by Ravi Khakhkhar

Make sure to:

确保:

  • send JSON object, not JSON String
  • included Hymanson on your classpath
  • 发送 JSON 对象,而不是 JSON 字符串
  • 将 Hymanson 包含在您的类路径中

Then you can add @RequestBody Employee employeeat the controller's method signature.

然后您可以添加 @RequestBody Employee employee控制器的方法签名。

回答by nobeh

I suppose you're using Spring 3.0+. Take a look at Spring Source blog post on JSON simplifications. It seems that you're half way there already.

我想你正在使用 Spring 3.0+。查看有关JSON 简化的Spring Source 博客文章。看来你已经成功了一半。

回答by Eugene Ryzhikov

Use JSON mapping librarysuch as Hymansonor Gson

使用 JSON 映射库,例如HymansonGson

Your code would look approximately as :

您的代码大致如下:

Employee e;
try {
    e = objectMapper.readValue(body, Employee .class);
} catch (IOException e) {
    throw new IllegalArgumentException("Couldn't parse json into a employee", e);
}

If you using Spring 3 or higher, there is even simpler way to do it: http://blog.springsource.org/2010/01/25/ajax-simplifications-in-spring-3-0/

如果您使用 Spring 3 或更高版本,还有更简单的方法:http: //blog.springsource.org/2010/01/25/ajax-simplifications-in-spring-3-0/