2016-07-11 3 views
2

내 컨트롤러에서 같은 방법으로 XML 및 JSON 응답을 생성하려고합니다. JSON은 클래스 패스에 있기 때문에 JSON이 봄에 기본이라고 봤습니다. 그러나 XML의 경우 JAXB 종속성을 추가 한 다음 내 모델에 JAXB 주석을 추가해야했습니다. 또한 @RequestMapping 주석의 produce 속성을 변경해야했습니다.스프링 4 mvc REST XML 및 JSON 응답

이제 기본 동작이 변경되어 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 protected]"); 
     p.setName("Amar"); 
     return p; 
    } 

} 

모델 클래스 -

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

빌드 파일 : -

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' 
    } 
} 

내가 잘못 뭐하는 거지 ??? 여기에 도움을 주시면 감사하겠습니다.

감사합니다, 요청이 application/json로 설정 Accept 헤더를 포함해야 서버에서 json 응답을 얻기 위하여

+1

JAXB는 JDK의 일부이므로 종속성을 추가 할 필요가 없습니다. 반환되는 내용은 수락 헤더 (및 순서)와 호출 할 URL (.json 또는 .xml과 같은 확장이 반환되는 항목에 영향을 미침)에 따라 결정됩니다. 잭슨이 JAXB 어노테이션을 이해하기를 원한다면 JAXB 어노테이션에 올바른 JAXB 의존성을 포함시켜야한다. –

+0

감사합니다. 답변으로 의견을 수락 할 수 없으므로 아래 내용을 수락했습니다. –

답변

5

아마르.

+0

이것은 작동합니다, 고마워요. 요청 헤더가 트릭을 수행 할 것이므로 컨텐트 유형이 설정되었다고 생각했지만 헤더를 수락했습니다. –

3

Json 또는 XML로 응답을 보내려면 한 가지 해결책은 Content Negotiation Strategy를 사용하는 것입니다. /person.json 또는 /person.xml과 같은 URL을 사용할 수 있습니다. 이것들은 json 또는 xml 응답을 생성합니다. 컨트롤러에 추가 할

@Configuration 
@EnableWebMvc 
public class WebConfig extends WebMvcConfigurerAdapter { 

    @Override 

     public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { 
     configurer.favorPathExtension(false). 
       favorParameter(true). 
       parameterName("mediaType"). 
       ignoreAcceptHeader(true). 
       useJaf(false). 
       defaultContentType(MediaType.APPLICATION_JSON). 
       mediaType("xml", MediaType.APPLICATION_XML). 
       mediaType("json", MediaType.APPLICATION_JSON); 
     } 
    } 

필요가 생산 = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE} :하지만 먼저, 당신은 자신의 메인 스프링 부트 클래스를 구성해야합니다. Here is an example 희망이 도움이 될 것입니다.

+0

감사합니다.이 정보를 제공해 주셔서 감사합니다. –

+0

This is too works !!!!!! –

+0

좋습니다. 너를 돕기에 행복 하네. – Pracede