【发布时间】:2014-11-26 17:03:58
【问题描述】:
我在guide 之后使用 Jersey 创建了一个非常简单的 RESTful 服务。 我将生成的示例代码调整为具有多态结构,其中 Animal 是基类,Sheep 和 Goat 继承自它:
@XmlRootElement
public abstract class Animal {
public Animal() {}
}
@XmlRootElement
public class Sheep extends Animal {
public String fur;
public Sheep() {this.fur = "curly";}
}
@XmlRootElement
public class Goat extends Animal {
public String color;
public Goat() {this.color = "yellow";}
}
以及产生响应的以下资源类:
@Path("animal")
public class MyResource {
@GET
@Path("{animal}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Animal getIt(@PathParam("animal") String animal) {
return (animal.equals("sheep")) ? new Sheep() : new Goat();
}
}
我的 pom.xml 中的项目依赖项是:
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
</dependencies>
当我在服务器上的 Eclipse 中运行应用程序时(如果重要,使用 Tomcat v8.0)并尝试请求 XML 响应,例如在浏览器中,输出正确如下:
<sheep>
<fur>curly</fur>
</sheep>
或者如果我要求一只山羊:
<goat>
<color>yellow</color>
</goat>
但是一旦我请求 JSON 响应,输出就是一个空的 JSON 文档:{} 我使用 curl 来获取 JSON 媒体类型,如下所示:
curl -H "Accept: application/json" http://localhost:8080/simple-service-webapp/api/animal/goat
我需要进行哪些配置或更改才能获得代表正确对象的 JSON 响应?我是这个话题的新手,我希望这个问题很清楚。谢谢。
PS: 如果方法 getIt 的返回类型设置为 e.g.返回 Sheep 和 Sheep 对象,JSON 响应是正确的,所以我想我需要以某种方式映射继承,以便它识别返回的类型,但我不知道该怎么做。
【问题讨论】:
标签: java json rest jersey moxy