SpringMVC自定義返回XML/JSON資料
阿新 • • 發佈:2019-02-19
1、新增jackson依賴
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.0'
2、開啟<mvc:annotation-driven />
註解
3、編寫JavaBean
package cn.bjut.entity;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
4、編寫Controller
@ResponseBody
@RequestMapping (value = "/json", method = RequestMethod.GET)
public Person test1() {
Person person = new Person();
person.setAge(25);
person.setName("你大爺");
return person;
}
- 如果沒有配置Person類的
@XmlRootElement
註解,那麼只會返回JSON資料,無論Accept是什麼 - 如果配置了Person類的XML註解,那麼如果Accept含有
applicatin/xml
, 就會返回xml資料
因為瀏覽器預設包含了Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
所以直接訪問會返回XML資料 - 如果改為
accept: "application/json"
,即可返回JSON資料