type=Not Acceptable, status=406 Spring Rest 生成 XML 时出错

İlk*_*nel 3 rest spring-boot

我正在 Spring Rest 和我的 Spring Rest 应用程序中工作,如果我尝试生成 json 一切都可以。我可以在浏览器上看到它。没有错误。

\n\n

但如果我想生成 XML,我可以使用 Produces = "application/xml" 或 Produces=MediaType.TEXT_XML_VALUE 并\n我收到此错误:

\n\n
Whitelabel Error Page\n\nThis application has no explicit mapping for /error, so you are seeing this as a fallback.\n\nSun Oct 23 18:30:51 EEST 2016\nThere was an unexpected error (type=Not Acceptable, status=406).\nCould not find acceptable representation\n
Run Code Online (Sandbox Code Playgroud)\n\n

我的其余代码是:

\n\n
package getExample;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.springframework.http.MediaType;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport pojo.Address;\nimport pojo.Person;\n\n@RestController\npublic class GetExampleController {\n\n    @RequestMapping(value = "getExample",method=RequestMethod.GET,produces=MediaType.TEXT_XML_VALUE)\n    public List<Person> getExample1(@RequestParam(value = "personId", defaultValue = "0") String id) {\n        List<Person> personList = new ArrayList<>();\n        Person person1 = new Person("1", "ilkay", "g\xc3\xbcnel",\n                new Address("Cennet Mah.", "K.\xc3\x87ekmece", "\xc4\xb0stanbul", "T\xc3\x9cRK\xc4\xb0YE"));\n        personList.add(person1);\n\n        Person person2 = new Person("2", "alican", "akku\xc5\x9f",\n                new Address("Cennet Mah.", "K.\xc3\x87ekmece", "\xc4\xb0stanbul", "T\xc3\x9cRK\xc4\xb0YE"));\n        personList.add(person2);\n\n        Person person3 = new Person("3", "mustafa", "demir",\n                new Address("Cennet Mah.", "K.\xc3\x87ekmece", "\xc4\xb0stanbul", "T\xc3\x9cRK\xc4\xb0YE"));\n        personList.add(person3);\n\n        if (id.equals("0")) {\n            return personList;\n        }\n        else {\n            return personList.subList(Integer.parseInt(id)-1, Integer.parseInt(id));\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

错误是什么?为什么我可以获得 XML 输出?我该如何解决这个问题?

\n

ale*_*xbt 5

你需要添加jackson-dataformat-xml\ 的依赖项:

\n
<dependency>\n    <groupId>com.fasterxml.jackson.dataformat</groupId>\n    <artifactId>jackson-dataformat-xml</artifactId>\n</dependency>\n
Run Code Online (Sandbox Code Playgroud)\n

否则,您可以使用 JAXB 注释来注释您的 bean。

\n

Spring文档

\n
\n

如果类路径上有 Jackson XML 扩展 (jackson-dataformat-xml),\n它将用于呈现 XML 响应,并且\n与我们用于 JSON 的示例相同。

\n

...

\n

如果 Jackson\xe2\x80\x99s XML 扩展不可用,则将使用 JAXB(JDK 中默认提供的),并附加要求\n[您的类] 注释为 @XmlRootElement...

\n

...

\n

要让服务器呈现 XML 而不是 JSON,您可能必须发送\nan Accept: text/xml 标头(或使用浏览器)。

\n
\n