是否有方便的方法将具有嵌套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;
}
as
{
"serial_no" : null,
students : [
{
"strs" : ["athlete", "grammarian"],
"name" : "John Smith",
"city" : "Auckland"
},
{
"strs" : ["postmaster", "swimmer"],
"name" : "Jane Doe",
"city" : "Sydney"
}
]
}
在Spring中执行此操作的最佳方法是什么?到目前为止,我遇到的示例似乎是简单的类,没有嵌套。
答案 0 :(得分:0)
要从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;
}