我按照此 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 的返回类型设置为例如Sheep 和 Sheep 对象已返回,JSON 响应是正确的,所以我想我需要以某种方式将继承映射到某个地方,以便它识别返回的类型,但我不知道该怎么做。
最佳答案
似乎这需要使用 @XmlSeeAlso
@XmlRootElement
@XmlSeeAlso({Sheep.class, Goat.class})
public abstract class Animal {
public Animal() {}
}
C:\>curl -H "Accept:application/json" http://localhost:8080/api/animal/sheep
{"type":"sheep","fur":"curly"}
关于java - Jersey - 如果使用多态性,JSON 响应为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27154884/