3

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

Java Code:

@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:

<%@ 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>

3 Answers 3

1

Make sure to:

  • send JSON object, not JSON String
  • included Jackson on your classpath

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

Use JSON mapping library such as Jackson or Gson

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.