【问题标题】:Jersey - JSON response empty if polymorphism usedJersey - 如果使用多态,则 JSON 响应为空
【发布时间】: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


    【解决方案1】:

    看来这需要使用@XmlSeeAlso

    @XmlRootElement
    @XmlSeeAlso({Sheep.class, Goat.class})
    public abstract class Animal {
        public Animal() {}
    }
    

    C:\&gt;curl -H "Accept:application/json" http://localhost:8080/api/animal/sheep
    {"type":"sheep","fur":"curly"}

    【讨论】:

    • 这个可行,谢谢,还有没有办法摆脱“type”属性?
    • 嗯。我什至没有注意到这一点。让我看看
    • 我想你会找到答案here。没有时间测试它。但还要注意,使用 jersey-media-json-jackson 而不是 MOXy,您不会得到这种行为
    • 我最终选择了 jackson,出于某种原因,它甚至比 moxy 更快地生成 JSON。我想为你的答案投票,但我的评分不允许,我可能会在足够时回来。
    猜你喜欢
    • 1970-01-01
    • 2014-12-29
    • 2020-07-03
    • 1970-01-01
    • 2014-05-02
    • 2016-07-26
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多