Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a object into JSON in REST service by Spring MVC

I'm trying to create a REST service using Spring MVC and it's working if I'm returning a plain string. My requirement is to return a JSON string of the Java object. Don't know how to achieve this by implicit conversion.

Here is my code:

StudentService.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!!!";
    }
}

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

Here http://localhost:8080/schoolmangement/rest/student/test URL is returning "Test REST Service!!!"

But, http://localhost:8080/schoolmangement/rest/student/1 URL throwing HTTP Status code 406 with error message:

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

like image 408
Roul Avatar asked Mar 16 '15 11:03

Roul


People also ask

How does spring boot convert object to JSON?

When Jackson is on the classpath an ObjectMapper bean is automatically configured. The spring-boot-starter-json is pulled with the spring-boot-starter-web . In Spring objects are automatically convered to JSON with the Jackson library. Spring can be configured to convert to XML as well.

Can we create REST API using Spring MVC?

The REST API support was introduced in Spring from version 3.0 onwards; since then, it has steadily evolved to the present day. We can create REST resources in the following ways: Using controllers which are used to handle HTTP requests such as GET, POST, PUT, and so forth.

How pass JSON object in post request in spring boot?

Send JSON Data in POST Spring provides a straightforward way to send JSON data via POST requests. The built-in @RequestBody annotation can automatically deserialize the JSON data encapsulated in the request body into a particular model object. In general, we don't have to parse the request body ourselves.


1 Answers

Finally I got solution using Jackson library along with Spring MVC. I got this solution from an example of Journal Dev( http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program )

So, the code changes I have done are:

  • Include the library in Maven.
  • Add JSON conversion Servlet into servlet-context.xml.
  • Change the Model into Serializable.

I didn't made any changes to my REST service controller. By default it converts into JSON.

like image 126
Roul Avatar answered Oct 10 '22 06:10

Roul