我正在使用 Jetty 服务器、Jersey 库和 JAX-RS 学习 REST 服务。
我有以下方法,它应该返回所有 Customer 对象(以 xml 或 json 格式):
@GET
@Produces({ "application/xml", "application/json" })
public Collection<Customer> getAll() {
List<Customer> customerList = new ArrayList<Customer>(customerDB.values());
return customerList;
}
客户对象定义为:
package com.rest.domain;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
@XmlRootElement(name = "customer")
public class Customer {
// Maps a object property to a XML element derived from property name.
@XmlElement
public int id;
@XmlElement
public String firstname;
@XmlElement
public String lastname;
@XmlElement
public String email;
}
如果我从curl发送以下命令,我会收到一个xml响应(而不是按照请求的json):
curl -H "Content-Type: application/json" -X GET http://localhost:8085/rest/customers/
如果我请求 json,为什么它返回 xml 响应?
最佳答案
您正在发送一个 Content-Type:
header ,它指的是您发送到服务器的内容类型(因为它是 GET,所以您实际上并没有发送任何内容)。我认为您可能希望将其更改为 Accept: application/json
header ,它告诉服务器您希望接收的响应类型。
关于java - 返回 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44681694/