2
votes

I'm trying to figure out a way to pass a complex object via json with spring mvc 3.1. I am also using knockoutjs, so take the ko.toJSON to be equivalent to JSON.stringify.

DeployT

here is the ajax call:

$.ajax({
            url: "/doAction",
            type: "post",
            data: ko.toJSON({"complexObjectA": ko.toJSON(self.complexObjectA()), "complexObjectB": ko.toJSON(self.complexObjectB()), "id": "", "text": ""}),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            // callback handler that will be called on success
            success: function (response, textStatus, jqXHR) {
                //dosomething
            },
            // callback handler that will be called on error
            error: function (jqXHR, textStatus, errorThrown) {
                // log the error to the console

            },
            // callback handler that will be called on completion
            // which means, either on success or error
            complete: function () {
                //dosomething
            }
        });

The spring controller code looks like:

    @RequestMapping(value = "/doAction", method = RequestMethod.POST)
    @ResponseBody
    public String doAction(@RequestBody MyForm form, HttpServletRequest request, HttpServletResponse response) {

and MyForm is defined as such:

public class MyForm {
private ComplexObjectA complexObjectA;
private ComplexObjectB complexObjectA;
private String id;
private String text;

with the appropriate public getter/setters.

When I attempt to make this call, I get a error 400 The request sent by the client was syntactically incorrect ().

The complex objects are both obtained via a json get earlier and they get serialized just fine from the object to json and into js objects.

Do I need to create a special deserializer with Jackson in order to do this?

1

1 Answers

1
votes

As you say that your complex objects serialized successfully before, I can guess that your Spring config files are okay and Jackson is configured properly. I think that you don't need to create a separate serializer/deserializer for MyForm class.

A 400 error "bad request" can come up for example if you make your jQuery AJAX call when a user clicks a link with a non-empty href, so the browser tries to perform the default action. In that case you can see that a request header still has the type "text/html", though you are trying to send "application/json".