0

How do you instantiate a custom object from a request param? (I have tried both @ModelAttribute and @RequestParam)

@RequestMapping(method = RequestMethod.POST)
public String newPerson(@ModelAttribute(value = "personModel") 
                          Person person, BindingResult result) {
// Person has just firstname and lastname fields
 }

I try to call this with jQuery using the following code:

var PersonText = '["firstname":"John", "lastname":"Someone"]';
$.ajax({
type : 'POST',
url : "/addnewperson.do",
data : {'personModel' : personText},
datatype : 'json',
success : function(data) {
    var obj = jQuery.parseJSON(data);
}
});

In fact my original plan was to send an entire list of person objects over to the controller, but since that didn't work I reverted back to a single object, but now that doesn't work either.

EDIT: the param doesn't have to be JSON, I just thought it would make sense to serialize the Javascript object as JSON over to the Spring Controller.

2 Answers 2

0

I was able to get this to work with the following call from Javascript (jquery)

$.post("/modifylist.do",{ firstname: "John", lastname: "Doe" } );

However, I'd still really like to know how to get this to work with arrays or lists, i.e. the parameter being Person[] or List<Person> instead.

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

Comments

-1
@RequestMapping(method = RequestMethod.POST)
public String newPerson(@RequestParam("personModel") String person,    BindingResult result) {
Gson gson = new Gson();
Person finalObject = gson.fromJson(person, Person.class);
// Person has just firstname and lastname fields
 }

You can use it like this. and for list you can use something like :

Gson gson = new Gson();
List<Person> finalObjectList = gson.fromJson(Person, new TypeToken<List<Person>>() {
    }.getType());

I hope that helps you :)

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.