Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

receiving json and deserializing as List of object at spring mvc controller

My code is as below:

controller

@RequestMapping(value="/setTest", method=RequestMethod.POST, consumes="application/json") public @ResponseBody ModelMap setTest(@RequestBody List<TestS> refunds, ModelMap map) {     for(TestS r : refunds) {         System.out.println(r.getName());     }     // other codes } 

TestS pojo

public class TestS implements Serializable {     private String name;     private String age;     //getter setter } 

Json request

var z = '[{"name":"1","age":"2"},{"name":"1","age":"3"}]'; $.ajax({     url: "/setTest",     data: z,     type: "POST",     dataType:"json",     contentType:'application/json'                }); 

It's giving this error

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.air.cidb.entities.TestS

I am using spring 3.1.2 and jackson 2.0.4

Edit: I want to receive list of TestS objects at my controller method, and process them. I am not able to find if I am sending wrong json or my method signature is wrong.

like image 499
HKumar Avatar asked Apr 11 '14 12:04

HKumar


1 Answers

Here is the code that works for me. The key is that you need a wrapper class.

public class Person {      private String name;     private Integer age;      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public Integer getAge() {         return age;     }      public void setAge(Integer age) {         this.age = age;     }      @Override     public String toString() {         return "Person [name=" + name + ", age=" + age + "]";     } 

A PersonWrapper class

public class PersonWrapper {      private List<Person> persons;      /**      * @return the persons      */     public List<Person> getPersons() {         return persons;     }      /**      * @param persons the persons to set      */     public void setPersons(List<Person> persons) {         this.persons = persons;     } } 

My Controller methods

@RequestMapping(value="person", method=RequestMethod.POST,consumes="application/json",produces="application/json")     @ResponseBody     public List<String> savePerson(@RequestBody PersonWrapper wrapper) {         List<String> response = new ArrayList<String>();         for (Person person: wrapper.getPersons()){         personService.save(person);          response.add("Saved person: " + person.toString());     }         return response;     } 

The request sent is json in POST

{"persons":[{"name":"shail1","age":"2"},{"name":"shail2","age":"3"}]} 

And the response is

["Saved person: Person [name=shail1, age=2]","Saved person: Person [name=shail2, age=3]"] 
like image 188
Shailendra Avatar answered Sep 23 '22 15:09

Shailendra