Reputation: 45
I need to execute this URL: http://localhost:8080/FitiProject/student and the response needs to be a json string containing the data of a Student
object.
Here is my code:
package spring.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import model.Student;
@Controller
public class PruebaController {
@RequestMapping("/student")
public @ResponseBody Student getStudent(){
return new Student(2, "h");
}
}
This is Student.java
package model;
public class Student {
private int edad;
private String nombre;
public Student(int edad, String nombre) {
super();
this.edad = edad;
this.nombre = nombre;
}
public int getEdad() {
return edad;
}
public void setEdad(int edad) {
this.edad = edad;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
When I do a GET request on the URL, I don't get a JSON response instead I get a 406 error code. How can I solve this?
I'm using Jackson 1.9 and Spring 4.1.
Upvotes: 0
Views: 5827
Reputation: 943
Use the RestController : org.springframework.web.bind.annotation.RestController
to get automatic conversion of the responseBody into a JSON Format
.
Upvotes: 0
Reputation: 446
If you're already using Jackson, you could try using the ObjectMapper
class:
ObjectMapper mapper = new ObjectMapper();
System.out.println("Object in JSON:\n" + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object));
Upvotes: 1
Reputation: 85781
Your getStudent
method lacks the content type of the response, otherwise Spring won't know to which format convert the Student
. This can be done by using produces
attribute in @RequestMapping
.
//"produces" will tell Spring to which format convert the data
//"method" will tell Spring which HTTP method should be handled for this URL
@RequestMapping(value="/student",
produces="application/json; charset=UTF-8",
method=RequestMethod.GET)
public @ResponseBody Student getStudent(){
return new Student(2, "h");
}
When executing a request to your URL, make sure that the client uses the following header: Content-Type: application/json
It's worth to mention that your project needs to have jackson libraries in order to work.
Upvotes: 2
Reputation: 5758
Since you are using @ResponseBody
annotation the response will be automatically converted to JSON. Make sure you include jackson mapper library in your class path.
If you are using Maven, you can add the jackson dependency as follows :
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.8.2</version>
</dependency>
Upvotes: 0