通过Spring MVC在REST服务中将对象转换为JSON

2022-09-03 06:21:33

我正在尝试使用Spring MVC创建一个REST服务,如果我返回一个普通字符串,它就可以工作了。我的要求是返回 Java 对象的 JSON 字符串。不知道如何通过隐式转换来实现这一点。

这是我的代码:

学生服务.java

package com.spring.schoolmanagement.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring.schoolmanagement.dao.CourseDAOImpl;
import com.spring.schoolmanagement.dao.StateDAOImpl;
import com.spring.schoolmanagement.dao.StudentDAOImpl;
import com.spring.schoolmanagement.model.Student;

@Controller
@RequestMapping("/rest/student")
public class StudentService {

    @Autowired
    private CourseDAOImpl courseService;
    @Autowired
    private StudentDAOImpl studentService;
    @Autowired
    private StateDAOImpl stateService;


    @RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "Accept=*/*")
    @ResponseBody
    public Student home(@PathVariable int id) {
        return this.studentService.getById(id);
    }

    @RequestMapping(method = RequestMethod.GET, headers = "Accept=*/*")
    @ResponseBody
    public List<Student> getAll() throws Exception {
        return this.studentService.getAll();
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET, headers = "Accept=*/*")
    @ResponseBody
    public String test() {
        return "Test REST Service!!!";
    }
}

学生.java

package com.spring.schoolmanagement.model;

import java.util.Date;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

public class Student extends Contact{
    private int id;

    @NotEmpty
    @Size(max = 30)
    private String firstName, lastName;
    //private String lastName;

    @DateTimeFormat(pattern="MM/dd/yyyy")
    private Date DOB, DOA;
    //private Date DOA;

    @NotEmpty
    @Email
    private String email;
    private String password;
    private int courseID;
    private String courseName;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDOB() {
        return DOB;
    }
    public void setDOB(Date dOB) {
        DOB = dOB;
    }
    public Date getDOA() {
        return DOA;
    }
    public void setDOA(Date dOA) {
        DOA = dOA;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getCourseID() {
        return courseID;
    }
    public void setCourseID(int courseID) {
        this.courseID = courseID;
    }
    public String getCourseName() {
        return courseName;
    }
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
}

此处 http://localhost:8080/schoolmangement/rest/student/test URL 返回“测试 REST 服务!!!”

但是,http://localhost:8080/schoolmangement/rest/student/1 URL引发HTTP状态代码406并显示错误消息:

此请求标识的资源只能根据请求“接受”标头生成具有不可接受的特征的响应。


答案 1

最后,我得到了使用Jackson库和Spring MVC的解决方案。我从Journal Dev(http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program )

因此,我所做的代码更改是:

  • 将库包含在 Maven 中。
  • 将 JSON 转换 Servlet 添加到 servlet-context.xml。
  • 将模型更改为可序列化。

我没有对 REST 服务控制器进行任何更改。默认情况下,它会转换为 JSON。


答案 2

您始终可以在 Web 方法上方添加内容,也可以指定返回 json。然后在类之上,您可以从包中添加。@Produces("application/json")produces="application/json"Student@XmlRootElementjavax.xml.bind.annotation

请注意,直接返回模型类可能不是一个好主意。只是一个建议。

呵呵。