Ama*_*Dev 2 rest spring json spring-mvc spring-boot
我试图从我的控制器中的相同方法生成XML和JSON响应.我用Google搜索并发现JSON是spring的默认值,因为jackson在classpath上.但对于XML,我必须添加JAXB依赖项,然后使用JAXB注释注释我的模型.另外,我不得不更改@RequestMapping注释的produce属性.
现在,我的默认行为已更改,它返回XML响应.我想在使用值application/json将content-Type标头添加到我的请求后,我的响应将是JSON,但遗憾的是情况并非如此.以下是我的代码: -
package com.example.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.domain.Person;
@RestController("person")
public class PersonController {
@RequestMapping(name ="getperson", produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
public Person getPerson() {
Person p = new Person();
p.setAge(28);
p.setEmail("email@gmail.com");
p.setName("Amar");
return p;
}
}
Run Code Online (Sandbox Code Playgroud)
型号类: -
package com.example.domain;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
//@XmlElement
private String name;
//@XmlElement
private int age;
private String email;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
@XmlElement
public void setEmail(String email) {
this.email = email;
}
}
Run Code Online (Sandbox Code Playgroud)
构建文件: -
buildscript {
ext {
springBootVersion = '1.3.6.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
jar {
baseName = 'demo'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-aop')
compile('org.springframework.boot:spring-boot-starter-web')
compile('javax.xml.bind:jaxb-api:2.2.12')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
eclipse {
classpath {
containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
}
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么 ???这里的任何帮助非常感谢.
谢谢,
阿马尔
| 归档时间: |
|
| 查看次数: |
6336 次 |
| 最近记录: |