JSON,泽西岛和杰克逊的多态性 [英] Polymorphism in JSON, Jersey and Jackson

查看:116
本文介绍了JSON,泽西岛和杰克逊的多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jackson和Jersey支持多态类而不是JSON吗?

Does Jackson with Jersey support polymorphic classes over JSON?

比方说,我有一个Parent类和一个继承它的Child类。而且,假设我想使用JSON发送&通过HTTP接收父母和子女。

Let's say, for instance, that I've got a Parent class and a Child class that inherits from it. And, let's say I want to use JSON to send & receive both Parent and Child over HTTP.

public class Parent {
...
}

public class Child extends Parent {
...
}

我考虑过这种实现:

@Consumes({ "application/json" }) // This method supposed to get a parent, enhance it and return it back
    public @ResponseBody 
    Parent enhance(@RequestBody Parent parent) {
    ...
    }

问题:如果我给这个函数(当然是通过JSON)一个Child对象,它会起作用吗?孩子的额外会员字段也会被序列化吗?
基本上,我想知道这些框架是否支持多态消费&回复。

Question: If I give this function (through JSON of course) a Child object, will it work? Will the Child's extra member fields be serialized, as well ? Basically, I want to know if these frameworks support polymorphic consume & respond.

BTW,我正在使用Spring MVC。

BTW, I'm working with Spring MVC.

推荐答案

Jackson确实支持多态性,

Jackson does support polymorphism,

在您的子类中使用名称注释:

In your child class annotate with a name:

 @JsonTypeName("Child_Class")
 @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectType")
 public class Child extends Parent{
 ....
 }

在父级中指定子类型:

In parent you specify sub types:

@JsonSubTypes({ @JsonSubTypes.Type(value = Child.class), @JsonSubTypes.Type(value = SomeOther.class)}) 
public class Parent {
    ....
}

这篇关于JSON,泽西岛和杰克逊的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆