我正在 Spring Rest 和我的 Spring Rest 应用程序中工作,如果我尝试生成 json 一切都可以。我可以在浏览器上看到它。没有错误。
但是如果我想生成 XML,我可以使用 Produces = "application/xml"或 Produces=MediaType.TEXT_XML_VALUE 和 我收到此错误:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Oct 23 18:30:51 EEST 2016
There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation
我的其余代码是:
package getExample;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pojo.Address;
import pojo.Person;
@RestController
public class GetExampleController {
@RequestMapping(value = "getExample",method=RequestMethod.GET,produces=MediaType.TEXT_XML_VALUE)
public List<Person> getExample1(@RequestParam(value = "personId", defaultValue = "0") String id) {
List<Person> personList = new ArrayList<>();
Person person1 = new Person("1", "ilkay", "günel",
new Address("Cennet Mah.", "K.Çekmece", "İstanbul", "TÜRKİYE"));
personList.add(person1);
Person person2 = new Person("2", "alican", "akkuş",
new Address("Cennet Mah.", "K.Çekmece", "İstanbul", "TÜRKİYE"));
personList.add(person2);
Person person3 = new Person("3", "mustafa", "demir",
new Address("Cennet Mah.", "K.Çekmece", "İstanbul", "TÜRKİYE"));
personList.add(person3);
if (id.equals("0")) {
return personList;
}
else {
return personList.subList(Integer.parseInt(id)-1, Integer.parseInt(id));
}
}
}
错误是什么?为什么我可以获得 XML 输出?我该如何解决这个问题?
最佳答案
您需要添加jackson-dataformat-xml
的依赖项:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
否则,您可以使用 JAXB 注释来注释您的 Bean。
Spring documentation :
If you have the Jackson XML extension (jackson-dataformat-xml) on the classpath, it will be used to render XML responses and the very same example as we used for JSON would work.
...
If Jackson’s XML extension is not available, JAXB (provided by default in the JDK) will be used, with the additional requirement to have [your class] annotated as @XmlRootElement...
...
To get the server to render XML instead of JSON you might have to send an Accept: text/xml header (or use a browser).
关于rest - type=Not Acceptable, status=406 Spring Rest 生成 XML 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40204926/