是否有一种方便的方法将Java类与Java类的嵌套数组转换为JSON?例如,我想将以下类的实例转换为JSON:
public class Students {
private final String serial_no;
private final class InnerData {
private final String[] strs;
private final String name;
private final String city;
}
private final StudentList[] students;
}
{
"serial_no" : null,
students : [
{
"strs" : ["athlete", "grammarian"],
"name" : "John Smith",
"city" : "Auckland"
},
{
"strs" : ["postmaster", "swimmer"],
"name" : "Jane Doe",
"city" : "Sydney"
}
]
}
在春季最好的方法是什么?到目前为止,我遇到的例子似乎都是简单的类,没有嵌套。
要从spring对象返回JSON形式的java对象,需要两个简单的配置:1)在类路径中添加'jackson-mapper-asl'依赖项2)在控制器的方法
中添加@ResponseBody注释1)在类路径中添加'jackson-mapper-asl'依赖项
在spring mvc项目中,我们需要在pom.xml文件中添加一个'jackson-mapper-asl'依赖项,并且对象到json的转换是默认完成的。
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.10</version> </dependency>
2)添加@ResponseBody注释到控制器的方法
我们需要做的第二件事是对控制器的方法使用'@ResponseBody'注释。这将使spring理解方法返回值应该绑定到web响应体。
@RequestMapping("studentlist") public
@ResponseBody List<Student> getStudentList() { List<Student> studentList = new ArrayList<Student>(); studentList.add(new Student(23, "Meghna", "Naidu", "meghna@gmail.com", "8978767878")); studentList.add(new Student(3, "Robert", "Parera", "robert@gmail.com", "8978767878")); studentList.add(new Student(93, "Andrew", "Strauss", "andrew@gmail.com", "8978767878")); studentList.add(new Student(239, "Eddy", "Knight", "knight@gmail.com", "7978767878")); return studentList;
}