接收json并反序列化为spring mvc控制器上的对象列表

时间:2014-04-11 12:40:49

标签: spring spring-mvc jackson

我的代码如下:

控制器

@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请求

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

发出此错误

  

java.lang.ClassCastException:java.util.LinkedHashMap无法强制转换为com.gogoair.cidb.entities.TestS

我正在使用 spring 3.1.2 jackson 2.0.4

编辑:我希望在我的控制器方法中接收TestS对象列表,然后对其进行处理。我无法找到我发送错误的json或我的方法签名是错误的。

6 个答案:

答案 0 :(得分:41)

这是适合我的代码。关键是你需要一个包装类。

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 + "]";
    }

PersonWrapper类

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;
    }
}

我的控制器方法

@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;
    }

发送的请求是POST中的json

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

响应是

["Saved person: Person [name=shail1, age=2]","Saved person: Person [name=shail2, age=3]"]

答案 1 :(得分:12)

这是你尝试它的方式所不可能的。杰克逊解组工作在编译的java代码之后类型擦除。所以你的

public @ResponseBody ModelMap setTest(@RequestBody List<TestS> refunds, ModelMap map) 

真的只是

public @ResponseBody ModelMap setTest(@RequestBody List refunds, ModelMap map) 

(列表中没有泛型arg)。

解密List时,杰克逊创建的默认类型为LinkedHashMap

如@Saint所述,您可以通过为列表创建自己的类型来避免这种情况:

class TestSList extends ArrayList<TestS> { }

然后将控制器签名修改为

public @ResponseBody ModelMap setTest(@RequestBody TestSList refunds, ModelMap map) {

答案 2 :(得分:8)

asyncConnect(
  someStuff,
  connect(moreStuff)
)(props => <div />)

我们可以使用如上所示的Array。

答案 3 :(得分:1)

我相信这会解决问题

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

答案 4 :(得分:0)

对于我下面的代码工作,首先发送带有正确标题的json字符串

$.ajax({
        type: "POST",
        url : 'save',
        data : JSON.stringify(valObject),
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success : function(resp){
            console.log(resp);
        },
        error : function(resp){
            console.log(resp);
        }
    });

然后在Spring方面 -

@RequestMapping(value = "/save", 
                method = RequestMethod.POST,
                consumes="application/json")
public @ResponseBody String  save(@RequestBody ArrayList<KeyValue> keyValList) {
    //Saving call goes here
    return "";
}

这里KeyValue是简单的pojo,对应于你的JSON结构,你可以根据需要添加产生,我只是返回字符串。

我的json对象是这样的 -

[{"storedKey":"vc","storedValue":"1","clientId":"1","locationId":"1"},
 {"storedKey":"vr","storedValue":"","clientId":"1","locationId":"1"}]

答案 5 :(得分:0)

解决方案效果很好

public List<String> savePerson(@RequestBody Person[] personArray)  

对于此签名,您可以像

一样从邮递员传递Person数组
[
{
  "empId": "10001",
  "tier": "Single",
  "someting": 6,
  "anything": 0,
  "frequency": "Quaterly"
}, {
  "empId": "10001",
  "tier": "Single",
  "someting": 6,
  "anything": 0,
  "frequency": "Quaterly"
}
]

别忘了添加consumes标签:

@RequestMapping(value = "/getEmployeeList", method = RequestMethod.POST, consumes="application/json", produces = "application/json")
public List<Employee> getEmployeeDataList(@RequestBody Employee[] employeearray) { ... }