Is there any way to set up spring MVC to receive an Object with subobject?

Asked

Viewed 84 times

0

I have in my project a controller that receives data via jquery. But this data is converted into an object that contains subobject. that is:

class Teste{
    String a;
    String b;
    Test2 teste2;
}

class Test2{
    String c;
    String d;
}

No controller is receiving with the following code.

    @ResponseBody
    @RequestMapping(value = "/novo",
            method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public Teste cadastrar(Teste teste) {
        System.out.println("\n\n*******************TESTE*******************\n" + teste);
        return teste;
    }

This way the data is only sent by params query. So I cannot pass the subobjects. The ajax function used is the following.

$.ajax({
    type: 'POST',
    url: '/teste/novo?' + jQuery.param(teste),
    contentType: 'application/json',
    data: JSON.stringify(product),
    success: function (data) {
        //innerOptionsInHTML(data);
    }
}).done(function () {
    console.log("success");
}).fail(function () {
    console.log("error");
});

This way the subobjects are not passed to the server. In fact it only started to be passed when using Queryparams. Before that the function sent with application_json type. But it still didn’t work.

All this using spring MVC and need to pass the subobjects.

It would be more interesting if you could configure Spring MVC to receive the object via javascript in the form:

{
    a:"a",
    b:"b",
    teste:{
        c:"c",
        d:"d"
    }
}

without using params query.

  • Spring works naturally the way you want it to. If it is not working there is something wrong, maybe on the client side when mounting the object that is sent to the controller. Review the name of the variables, because in the example that posted your class Test has the class Teste2 and in JSON you created the subobject as a test and not teste2.

  • I got it. I don’t think I was compiling.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.