JAXB和继承 [英] JAXB and inheritance

查看:65
本文介绍了JAXB和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取一个JSON文件,如:

I am trying to read a JSON file like:

{
  "a": "abc",
  "data" : {
      "type" : 1,
      ...
  }
}

其中......部分可根据类型替换:

where the ... part is replaceable based on the type like:

{
  "a": "abc",
  "data" : {
      "type" : 1,
      "b" : "bcd"
  }
}

或:

{
  "a": "abc",
  "data" : {
      "type" : 2,
      "c" : "cde",
      "d" : "def",
  }
}

对于我的生活,我无法弄清楚用于实现这一目标的正确的JAXB注释/类。
如果需要,我没有在数据块之外移动类型变量的问题。

For the life of me I cannot figure out the proper JAXB annotations/classes to use to make this happen. I don't have an issue moving the type variable outside of the data block if needed.

我正在使用Glassfish 3.1.2.2。

I'm using Glassfish 3.1.2.2.

编辑:

根据Perception提供的代码,我做了一个快速的尝试......在glassfish中不起作用虽然:

Based on the code provided by Perception I did a quick attempt... doesn't work in glassfish though:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes(
{
    @JsonSubTypes.Type(value = DataSubA.class, name = "1"),
    @JsonSubTypes.Type(value = DataSubB.class, name = "2") 
})
@XmlRootElement
public abstract class Data implements Serializable 
{
    private static final long serialVersionUID = 1L;

    public Data() 
    {
        super();
    }
}

@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class DataSubA 
    extends Data 
{
    private static final long serialVersionUID = 1L;

    @XmlElement
    private BigDecimal expenditure;

    public DataSubA() {
        super();
    }

    public DataSubA(final BigDecimal expenditure) {
        super();
        this.expenditure = expenditure;
    }

    @Override
    public String toString() {
        return String.format("%s[expenditure = %s]\n", 
                             getClass().getSimpleName(), getExpenditure());
    }

    public BigDecimal getExpenditure() {
        return expenditure;
    }

    public void setExpenditure(BigDecimal expenditure) {
        this.expenditure = expenditure;
    }
}

@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class DataSubB 
    extends Data 
{
    private static final long serialVersionUID = 1L;

    @XmlElement
    private String name;

    @XmlElement
    private Integer age;

    public DataSubB() 
    {
        super();
    }

    public DataSubB(final String name, final Integer age) 
    {
        super();
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() 
    {
        return String.format("%s[name = %s, age = %s]\n", 
                             getClass().getSimpleName(), getName(), getAge());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class DataWrapper
{ 
    @XmlElement
    private Data data;

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }
}

还有一个简单的POST将其收入:

And a simple POST that takes it in:

@Stateless
@Path("x")
public class Endpoint
{
    @POST
    @Consumes(
    {
        MediaType.APPLICATION_JSON,
    })
    @Produces(
    {
        MediaType.APPLICATION_JSON,
    })
    public String foo(final DataWrapper wrapper)
    {
        return ("yay");
    }
}

当我传入JSON时:

{
    "data" : 
    {
        "type" : 1,
        "expenditure" : 1
    }
}

我收到如下消息:

Can not construct instance of Data, problem: abstract types can only be instantiated with additional type information
 at [Source: org.apache.catalina.connector.CoyoteInputStream@28b92ec1; line: 2, column: 5] (through reference chain: DataWrapper["data"])


推荐答案

DataClass 上添加一个 @XmlSeeAlso 注释,指定所有子类:

On the DataClass add an @XmlSeeAlso annotation that specifies all of the subclasses:

@XmlRootElement
@XmlSeeAlso({DataSubA.class, DataSubB.class})
public abstract class Data implements Serializable {

然后在每个子类上使用 @XmlType 注释以指定类型名称。

Then on each of the subclasses use the @XmlType annotation to specify the type name.

@XmlType(name="1")
public class DataSubA extends Data {






UPDATE

注意:我是 EclipseLink JAXB(MOXy) 领导和 JAXB(JSR-222)专家组。

T他JAXB(JSR-222)规范没有涵盖JSON绑定。 JAX-RS允许您通过JAXB注释指定JSON映射的方式有多种:

The JAXB (JSR-222) specification doesn't cover JSON-binding. There are different ways JAX-RS allows you to specify JSON mapping via JAXB annotations:


  1. JAXB实现以及像Jettison这样转换StAX的库事件到JSON(参见: http://blog.bdoughan .com / 2011/04 / jaxb-and-json-via-jettison.html

  2. 通过利用提供JSON绑定的JAXB impl(参见: http://blog.bdoughan.com/2011/08/json -binding-with-eclipselink-moxy.html

  3. 利用JSON绑定工具,支持某些JAXB元数据(即Jackson)。

由于您的模型似乎没有按预期对注释做出反应,我猜您正在使用方案3.下面我将演示解决方案,就像您使用的是方案2。

Since your model doesn't seem to be reacting as expected to the annotations I'm guessing you are using scenario 3. Below I will demonstrate the solution as if you were using scenario 2.

DataWrapper

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DataWrapper { 

    private String a;
    private Data data;

}

数据

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({DataSubA.class, DataSubB.class})
public class Data {

}

DataSubA

import javax.xml.bind.annotation.XmlType;

@XmlType(name="1")
public class DataSubA extends Data {

    private String b;

}

DataSubB

import javax.xml.bind.annotation.XmlType;

@XmlType(name="2")
public class DataSubB extends Data {

    private String c;
    private String d;

}

jaxb.properties

要将MOXy指定为JAXB提供程序,您需要在与域相同的包中包含名为 jaxb.properties 的文件具有以下条目的模型(请参阅: http:// blog .bdoughan.com / 2011/05 / specify-eclipselink-moxy-as-your.html ):

To specify MOXy as your JAXB provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

演示

import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {DataWrapper.class}, properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource json = new StreamSource("src/forum16429717/input.json");
        DataWrapper dataWrapper = unmarshaller.unmarshal(json, DataWrapper.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(dataWrapper, System.out);
    }

}

input.json /输出

MOXy可以读取数值 2 作为继承指标,但目前它将会总是把它写成2。我已打开以下增强请求来解决此问题: http://bugs.eclipse.org/407528

MOXy can read in the numeric value 2 as the inheritance indicator, but currently it will always write it out as "2". I have opened the following enhancement request to address this issue: http://bugs.eclipse.org/407528.

{
   "a" : "abc",
   "data" : {
      "type" : "2",
      "c" : "cde",
      "d" : "def"
   }
}

更多信息

以下链接将帮助您在JAX-RS实施中使用MOXy。

The following link will help you use MOXy in a JAX-RS implementation.

  • http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html

这篇关于JAXB和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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