【问题标题】:Response from spring-boot application in JSON format instead xml?来自 JSON 格式的 spring-boot 应用程序的响应,而不是 xml?
【发布时间】:2019-02-23 09:10:42
【问题描述】:

有spring-boot应用(web+jpa) 所以,我有控制器:

@RestController
public class CustomerController {
    @Autowired
    private CustomerService customerService;

@RequestMapping(value = "/customers", method = RequestMethod.GET)
public @ResponseBody List<Customer> findAllCustomers() {
    return customerService.findAllCustomers();
}

@RequestMapping(value = "/customers", method = RequestMethod.POST)
public void addCustomer(@RequestBody Customer customer) {
    customerService.addCustomer(customer);
}

型号:

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@Table(name="customer")
@XmlRootElement(name="customer")
public class Customer{
    @Id
    private String id;
    private String name;

    public Customer(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public Customer() {
    }

    public String getId() {
        return id;
    }

    @XmlElement
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
}

以及绑定jpa和rest的服务层。

当我请求时:

<customer>
    <id>first</id>
    <name>first name of metric</name>
</customer>

没关系,客户已添加到数据库中,但是,当我尝试获取所有客户时,响应为 json 格式,但我期望的是 xml。如何解决它的问题?

【问题讨论】:

  • 您不能公开 XML 列表。您还需要一个 XML 包装器。要返回的 XML 必须是有效的 XML。

标签: xml spring-boot


【解决方案1】:

将控制器方法标记为产生 application/xml 响应 (produces = MediaType.APPLICATION_XML_VALUE)。

【讨论】:

  • HTTP 状态 406 – 不可接受 描述 根据请求中收到的主动协商标头字段,目标资源没有用户代理可接受的当前表示,并且服务器不愿意提供默认表示。
  • 您的请求标头应包含“Accept”,其值为“application/xml”
【解决方案2】:

我认为您在调用 rest 方法时使用了错误的接受类型。

@ResponseBody 将根据外部客户端的能力和类路径上可用的库自动序列化返回值。如果 Jackson 在类路径上可用并且客户端已指示他们可以接受 JSON,则返回值将自动作为 JSON 发送。如果 JRE 为 1.7 或更高版本(这意味着 JRE 中包含 JAXB)并且客户端已表明可以接受 XML,则返回值将自动以 XML 格式发送。

【讨论】:

  • 如果我使用 Postman 进行测试,这对我意味着什么?添加 header Content-Type: application/xml ?
  • 您需要将Request header Accepts设置为application/xml。
  • @VladislavOsipenkov 你可以在这里阅读完整的答案stackoverflow.com/a/27793306/6572971
【解决方案3】:

添加解决

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2022-01-15
    • 1970-01-01
    • 2019-01-02
    相关资源
    最近更新 更多