返回JSON响应
问题描述:
我正在使用Jetty服务器,Jersey库和JAX-RS学习REST服务。返回JSON响应
我有以下的方法,该方法应该返回(在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/
为什么它返回一个xml响应,如果我要求json?
答
您正在发送Content-Type:
标题,它指向您发送给服务器的内容类型(因为它是GET,所以您实际上并未发送任何内容)。我想你可能想把它改成Accept: application/json
标题,它会告诉服务器你想接收的响应类型。
谢谢。就是这样! :) – TheAptKid