gpt4 book ai didi

spring - 在spring mvc Controller 接收json并反序列化为对象列表

转载 作者:IT老高 更新时间:2023-10-28 13:44:14 25 4
gpt4 key购买 nike

我的代码如下:

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

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 cannot be cast to com.air.cidb.entities.TestS

我正在使用 spring 3.1.2jackson 2.0.4

编辑:我想在我的 Controller 方法中接收 TestS 对象的列表,并处理它们。我无法找到我是否发送了错误的 json 或我的方法签名错误。

最佳答案

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

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

我的 Controller 方法

@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]"]

关于spring - 在spring mvc Controller 接收json并反序列化为对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23012841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com