【问题标题】:Returning a JSON response返回 JSON 响应
【发布时间】:2017-06-21 16:36:10
【问题描述】:

我正在学习使用 Jetty 服务器、Jersey 库和 JAX-RS 的 REST 服务。

我有以下方法,它应该返回所有客户对象(以 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 响应?

【问题讨论】:

    标签: java json curl jersey


    【解决方案1】:

    您正在发送一个 Content-Type: 标头,它指的是您要发送到服务器的内容类型(因为它是一个 GET,所以您实际上并没有发送任何内容)。我认为您可能希望将其更改为 Accept: application/json 标头,它告诉服务器您希望接收的响应类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2019-05-18
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 2014-12-18
      相关资源
      最近更新 更多