【问题标题】:Java Json serialization of Interface types接口类型的Java Json序列化
【发布时间】:2017-12-27 22:18:39
【问题描述】:

我有一个使用 spring rest 模板调用的 json web 服务。请求参数之一是接口。我正在寻找正确的注释组合(Jackson 或 Jaxb)来创建我的 json 请求。

我的请求需要如下所示:

{
    "request": {
        "specificAccountIdentifier": {
            "field1" : "value",
            "field2" : "value"
        }
    }
}

但是,现在,它的编组是这样的:

{
    "request": {
        "accountIdentifier": {
            "field1" : "value",
            "field2" : "value"
        }
    }
}

请求类:

@XmlRootElement
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class Request {
    @XmlAnyElement
    @XmlElementRefs({@XmlElementRef(type = SpecificAccountIdentifier.class)})
    private AccountIdentifier accountIdentifier;

    public Request() {
    }
}

帐户标识符:

@XmlSeeAlso(SpecificAccountIdentifier.class)
public interface AccountIdentifier extends Serializable {
}

特定帐户标识符:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@XmlType
public class SpecificAccountIdentifier implements AccountIdentifier {
    private static final long serialVersionUID = 8894475816041559L;
    private Long field1;
    private Long field2;
    ...class details...
}

我尝试了几种不同的 @JsonTypeInfo 组合,但都无法正常工作。

更新:

即使查看了下面的答案,我仍然无法工作,所以我最终只是编写了自己的自定义序列化程序。

【问题讨论】:

  • 您是否应该重命名私有 AccountIdentifier accountIdentifier;到私有 AccountIdentifier specificAaccountIdentifier?
  • 我会,但最终会有多种实现,所以仅仅改变变量名是行不通的。
  • 你的意思是这个“specificAccountIdentifier”是动态的,取决于哪个实现?
  • 是的,accountIdentifier 变量可以是几种不同的类型,我正在寻找一个注解,它将使用实现类名称作为 json 字段名称而不是接口变量名称。跨度>

标签: java json spring jaxb jackson


【解决方案1】:

发现 4 年前提出的类似问题,但您似乎可以用它来启动背后的想法。

基本上它是使用EclipseLink JAXB (MOXy) 和一个工厂方法来生成你的接口的实现。

https://stackoverflow.com/a/16155520/6039974

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多