我需要执行这个URL:http://localhost:8080/FitiProject/student并且响应需要是包含 Student
对象数据的 json 字符串。
这是我的代码:
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");
}
}
这是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;
}
}
当我对 URL 执行 GET 请求时,我没有收到 JSON 响应,而是收到 406 错误代码。我该如何解决这个问题?
我正在使用 Jackson 1.9 和 Spring 4.1。
最佳答案
您的getStudent
方法缺少响应的内容类型,否则Spring将不知道将Student
转换为哪种格式。这可以通过使用 @RequestMapping
中的 products
属性来完成。
//"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");
}
对您的 URL 执行请求时,请确保客户端使用以下 header :Content-Type: application/json
值得一提的是,您的项目需要有 Jackson 库才能工作。
关于java - 为什么使用 spring MVC 进行对象到 json 转换在这种情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133201/