我需要将实体对象转换为 json。我放
<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<array>
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
<property name="objectMapper">
<ref bean="JacksonObjectMapper" />
</property>
</bean>
</array>
</property>
</bean>
<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
到 servlet 配置文件,因此 Spring 可以自动将对象转换为 json 格式。但是 Spring 并没有这样做。我还将杰克逊罐子添加到项目中。
控制器方法
@RequestMapping(value = "/addData.html", method = RequestMethod.POST)
public @ResponseBody GroupStudent addNewGroup(@RequestBody GroupStudent group) {
return group;
}
小组学生
@Entity
@Table(name = "GroupStudent")
@NamedQueries({
@NamedQuery(name = "GroupStudent.getAllGroups", // get all groups
query = "select g from GroupStudent g"),
@NamedQuery(name = "GroupStudent.getGroupByName", // get group by name
query = "select g from GroupStudent g where g.groupStudentNumber = :name")
})
public class GroupStudent implements Serializable {
public GroupStudent() {}
public GroupStudent(String groupStudentNumber) {
this.groupStudentNumber = groupStudentNumber;
}
// create connectivity with table Student
private Set<Student> students = new HashSet<Student>();
@OneToMany(mappedBy = "groupStudent", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<Student> getStudents() {
return this.students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "group_id_seq")
@SequenceGenerator(name = "group_id_seq", sequenceName = "GroupStudent_seq", allocationSize = 1)
@Column(name = "GroupStudentId")
public Long getGroupStudentId() {
return this.groupStudentId;
}
public void setGroupStudentId(Long groupStudentId) {
this.groupStudentId = groupStudentId;
}
@Column(name = "GroupStudentNumber")
public String getGroupStudentNumber() {
return this.groupStudentNumber;
}
public void setGroupStudentNumber(String groupStudentNumber) {
this.groupStudentNumber = groupStudentNumber;
}
// table GroupStudent fields
private Long groupStudentId;
private String groupStudentNumber;
}
在浏览器中我发现我有 406 错误和错误窗口错误 [object Object]。
如果有人知道问题是什么,我将不胜感激。
谢谢你。