【发布时间】:2017-05-23 13:07:39
【问题描述】:
我的任务是构建一个带有基本身份验证的 REST API,输出一个 XML 文件。
我挣扎了一段时间让 XML 代替 JSON 出来,但我想我明白了。我已经注释了@XmlRootElement 和@XmlElements,果然,当我用浏览器访问API 时,XML 回来了,浏览器甚至告诉我“这个XML 文件似乎没有任何与之关联的样式信息。”耶! XML!任务完成了,对吧?
但是,当我使用 SoapUI 或 Postman 访问 API 时,它总是给我 JSON。告诉我没有 XML,即使是原始的也没有。这是 SoapUI 和 Postman 所做的事情,还是(更有可能)我需要更改我的代码中的某些内容以使其每次都成为 XML?
如果您能提供帮助,请提前致谢!
这是我认为相关的代码:
应用程序.java: 打包你好;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.web.context.*;
@SpringBootApplication
public class Application {
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(WebSecurityConfig.class);
}
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
地址.java
package hello;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="address")
public class Address {
private String street;
private String city;
private String stateZip;
public Address() {
this.street = "123 Main Street ";
this.city = "Concord";
this.stateZip = "NC-28027";
}
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getStateZip() {
return stateZip;
}
@XmlElement
public void setStreet(String street) {
this.street = street;
}
@XmlElement
public void setCity(String city) {
this.city = city;
}
@XmlElement
public void setStateZip(String stateZip) {
this.stateZip = stateZip;
}
}
AddressArray.java
package hello;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="addresses")
public class AddressArray {
public Address address1 = new Address();
public Address address2 = new Address();
public Address address3 = new Address();
}
AddressController.java
package hello;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AddressController {
@RequestMapping("/address")
public @ResponseBody AddressArray addresses() {
return new AddressArray();
}
}
在浏览器中访问它时,我得到了 XML,这确实是,但这是我在 Postman 或 SoapUI 中得到的那种响应,在 JSON 中仍然令人沮丧:
{
"address1": {
"street": "123 Main Street ",
"city": "Concord",
"stateZip": "NC-28027"
},
"address2": {
"street": "123 Main Street ",
"city": "Concord",
"stateZip": "NC-28027"
},
"address3": {
"street": "123 Main Street ",
"city": "Concord",
"stateZip": "NC-28027"
}
}
【问题讨论】:
-
我认为你应该将
produces ={ MediaType.APPLICATION_XML_VALUE}添加到@RequestMapping -
您可以做的另一件事是,在使用您的休息服务时将“Accept”键 - “application/xml”值添加到标头
-
这就是诀窍!问题解决了
-
是的,我知道这会奏效。很抱歉,这个问题没有显示出任何研究成果。