JAXB 2.x:如何从父类覆盖 XmlElement 注释 - 不可能的任务?

发布于 2024-10-11 15:20:44 字数 3483 浏览 5 评论 0 原文

为什么这是不可能的?看起来很简单,但它的表现并不像预期的那样。

摘要:A 类使用聚合的 DataA bean,而 B 类(A 类的子类)使用聚合的 DataB bean(而 DataB 扩展了 DataA)。

我编写了这些测试类来可视化并解释我的问题:

A 类:

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class A {

  private DataA source = new DataA();

  @XmlElement(name="source")
  public DataA getSource() {
    return source;
  }

  public void setSource(DataA source) {
    this.source = source;
  }

}

及其 DataA 类(我使用了 FIELD 注释,以便对所有字段进行编组):

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.FIELD)
public class DataA {

    public String string1 = "1";
    public String string2 = "2";

}

现在 B 类(A 类的子类):我的目标是重用A 的功能,并通过使用 DataB bean 重用 DataA bean 的属性:

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class B extends A {

  private DataB source = new DataB();

  public DataB getSource() {
    return this.source;
  }

  public void setSource(DataB source) {
    this.source = source;
  }

}

其相应的 DataB bean 如下所示:

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.FIELD)
public class DataB extends DataA {
    public String string3 = "3";
}

现在,当我编组 A 类的实例时,它会给出以下输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
  <source>
    <string1>1</string1>
    <string2>2</string2>
  </source>
</root>

当我编组 B 类的实例时,我得到了完全相同的结果:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
  <source>
    <string1>1</string1>
    <string2>2</string2>
  </source>
</root>

但我预计 string3 也会被编组,但它只是写入 bean DataA 的属性!为什么?从 OOP 角度思考时,这并不直观。

当我也在 B 类上设置 @XmlElement 注释时...如下所示:

@XmlElement
public DataB getSource() {
    return this.source;
}

...然后该属性将被编组两次,因为它曾经由父类和子类注释过。这也是我不想要的:

现在的输出是:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <source xsi:type="dataB" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <string1>1</string1>
        <string2>2</string2>
        <string3>3</string3>
    </source>
    <source>
        <string1>1</string1>
        <string2>2</string2>
        <string3>3</string3>
    </source>
</root>

我期望 JAXB 结果是以下 XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <source>
        <string1>1</string1>
        <string2>2</string2>
        <string3>3</string3>
    </source>
</root>

任何提示如何调整 JAXB 以产生预期结果? 感谢您的任何反馈。

Why is this not possible? It seems so simple but it does not behave as expected.

Summary: Class A uses an aggregated DataA bean whereas Class B (a subclass of Class A) is using an aggregated DataB bean (whereas DataB extends DataA).

I wrote these test classes to visualize and explain my question:

Class A:

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class A {

  private DataA source = new DataA();

  @XmlElement(name="source")
  public DataA getSource() {
    return source;
  }

  public void setSource(DataA source) {
    this.source = source;
  }

}

and its DataA class (I used the FIELD annotation so that all fields gets marshalled):

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.FIELD)
public class DataA {

    public String string1 = "1";
    public String string2 = "2";

}

And now the Class B (subclass of Class A): My goal is to reuse functionalities of A and also reuse the properties from the DataA bean by using the DataB bean:

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class B extends A {

  private DataB source = new DataB();

  public DataB getSource() {
    return this.source;
  }

  public void setSource(DataB source) {
    this.source = source;
  }

}

Its corresponding DataB bean looks like this:

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.FIELD)
public class DataB extends DataA {
    public String string3 = "3";
}

Now, when I marshall an instance of class A, it gives this output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
  <source>
    <string1>1</string1>
    <string2>2</string2>
  </source>
</root>

When I marshall an instance of class B, I get the very same result:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
  <source>
    <string1>1</string1>
    <string2>2</string2>
  </source>
</root>

But I expected that also string3 would get marshalled, but it is only writing the properties of bean DataA! WHY? This is not really intuitive when thinking in terms of OOP.

When I set the @XmlElement annotation also on the Class B... like this:

@XmlElement
public DataB getSource() {
    return this.source;
}

... then the property gets marshalled twice because it is once annotated by the parent class as well as by the child class. This is also what I do not want:

The output now is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <source xsi:type="dataB" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <string1>1</string1>
        <string2>2</string2>
        <string3>3</string3>
    </source>
    <source>
        <string1>1</string1>
        <string2>2</string2>
        <string3>3</string3>
    </source>
</root>

What I expected from JAXB as a result is the following XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <source>
        <string1>1</string1>
        <string2>2</string2>
        <string3>3</string3>
    </source>
</root>

Any hints how to tweak JAXB to produce the expected result??
Thanks for any feedback.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

眼角的笑意。 2024-10-18 15:20:44

只是不要在类 B 上注释源属性。源属性已映射到父类上,不应再次映射到子类上。由于您正在注释 get/set 方法,因此将在类 B 上调用适当的 get/set。

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class B extends A {

  private StringBuffer source = null;

  public String getSource() {
    return source.toString();
  }

  public void setSource(String source) {
    this.source = new StringBuffer(source);
  }
}

更新

Metro JAXB(参考实现)。当我使用 EclipseLink JAXB (MOXy) 运行这个更新的示例时,我得到以下输出

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <source>
      <string1>1</string1>
      <string2>2</string2>
   </source>
</root>
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b">
   <source xsi:type="dataB">
      <string1>1</string1>
      <string2>2</string2>
      <string3>3</string3>
   </source>
</root>

:可以使用以下代码重现:

package test;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(A.class, B.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        A a = new A();
        DataA da = new DataA();
        da.string1 = "1";
        da.string2 = "2";
        a.setSource(da);
        marshaller.marshal(a, System.out);

        B b = new B();
        DataB db = new DataB();
        db.string1 = "1";
        db.string2 = "2";
        db.string3 = "3";
        b.setSource(db);
        marshaller.marshal(b, System.out);
    }
}

要使用 MOXy 作为 JAXB 实现,您需要在模型包(测试)中提供名为 jaxb.properties 的文件,其中包含以下条目:

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

Just don't annotate the source property on class B. The source property was mapped on the parent class and should not be mapped again on the child class. Since you are annotating the get/set methods the appropriate get/set will be called on class B.

package test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class B extends A {

  private StringBuffer source = null;

  public String getSource() {
    return source.toString();
  }

  public void setSource(String source) {
    this.source = new StringBuffer(source);
  }
}

UPDATE

There may be a bug in the Metro JAXB (reference implementation). When I run this updated example with EclipseLink JAXB (MOXy) I get the following output:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <source>
      <string1>1</string1>
      <string2>2</string2>
   </source>
</root>
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b">
   <source xsi:type="dataB">
      <string1>1</string1>
      <string2>2</string2>
      <string3>3</string3>
   </source>
</root>

This can be reproduced with the following code:

package test;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(A.class, B.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        A a = new A();
        DataA da = new DataA();
        da.string1 = "1";
        da.string2 = "2";
        a.setSource(da);
        marshaller.marshal(a, System.out);

        B b = new B();
        DataB db = new DataB();
        db.string1 = "1";
        db.string2 = "2";
        db.string3 = "3";
        b.setSource(db);
        marshaller.marshal(b, System.out);
    }
}

To use MOXy as the JAXB implementation you need to supply a file named jaxb.properties in the model package (test) with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
苹果你个爱泡泡 2024-10-18 15:20:44

你不需要使用 MOXy..
只需更改 B 类并使用 @XmlAlso 即可。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "root")
public class B extends A {
}


@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({ DataA.class, DataB.class })
@XmlRootElement(name = "source")
@XmlType(name = "source")

public class DataA {
   private String string1 = "1";
   private String string2 = "2";
.....//getters and setters here
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "source")
public class DataB extends DataA {
    private String string3 = "3";
.....//getters and setters here
}

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlSeeAlso({ A.class, B.class }) 
@XmlRootElement(name = "root") 

public class A {

    private DataA source = new DataA();

    public DataA getSource() {
        return source;
    }

    public void setSource(DataA source) {
        this.source = source;
    }

}


 B b = new B();
        DataB db = new DataB();
        db.setString1("1");
        db.setString2("2");
        db.setString3("3");
        b.setSource(db);
        marshaller.marshal(b, System.out);

最后会写:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <source>
        <string1>1</string1>
        <string2>2</string2>
    </source>
</root>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <source xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="dataB">
        <string1>1</string1>
        <string2>2</string2>
        <string3>3</string3>
    </source>
</root>

you don't need to use MOXy..
Just change the Class B and use @XmlAlso.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "root")
public class B extends A {
}


@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({ DataA.class, DataB.class })
@XmlRootElement(name = "source")
@XmlType(name = "source")

public class DataA {
   private String string1 = "1";
   private String string2 = "2";
.....//getters and setters here
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "source")
public class DataB extends DataA {
    private String string3 = "3";
.....//getters and setters here
}

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlSeeAlso({ A.class, B.class }) 
@XmlRootElement(name = "root") 

public class A {

    private DataA source = new DataA();

    public DataA getSource() {
        return source;
    }

    public void setSource(DataA source) {
        this.source = source;
    }

}


 B b = new B();
        DataB db = new DataB();
        db.setString1("1");
        db.setString2("2");
        db.setString3("3");
        b.setSource(db);
        marshaller.marshal(b, System.out);

WILL FINALLY WRITE:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <source>
        <string1>1</string1>
        <string2>2</string2>
    </source>
</root>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <source xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="dataB">
        <string1>1</string1>
        <string2>2</string2>
        <string3>3</string3>
    </source>
</root>
暗地喜欢 2024-10-18 15:20:44

非常感谢布莱斯提供的所有这些提示。 MOXy 现在可以很好地与我的真实应用程序一起使用真实的豆子。好的!

我目前唯一的缺点是此配置代码中的最后一行不再起作用,因为 MOXy 当然使用另一个名称空间前缀映射机制。

你有这方面的指针吗?我搜索了 MOXy 文档并搜索了命名空间,但没有找到类似的内容。

    NamespacePrefixMapper mapper = new PreferredMapper();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", mapper);

    public static class PreferredMapper extends NamespacePrefixMapper {
      @Override
      public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
        return "z";
    }
}

Thanks a lot Blaise for all these hints. MOXy now works fine with my real application with real beans. nice!

The only drawback I currently have is that the last line in this configuration code does not work anymore because MOXy uses of course another namespace prefix mapping mechanism.

Do you have a pointer for this? I searched the MOXy documentation and search for namespace but nothing similar was found.

    NamespacePrefixMapper mapper = new PreferredMapper();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", mapper);

    public static class PreferredMapper extends NamespacePrefixMapper {
      @Override
      public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
        return "z";
    }
}
却一份温柔 2024-10-18 15:20:44

您可以使用此方法:

public interface Data {}

@XmlTransient
public abstract class A {
       private Data data;

       public Data getData(){
              return data;
       }

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

@XmlAccessorType(XmlAccessType.NONE)
public class ClassA extends A {

       // DataA implements Data
       @XmlElement(type=DataA.class)
       public Data getData(){
              return super.getData();
       }

       public void setData(DataA data){
              super.setData(data);
       }
}

@XmlAccessorType(XmlAccessType.NONE)
public class ClassB extends A {
       // DataB implements Data
       private DataB data;

       @XmlElement(type=DataB.class)
       public DataA getData(){
              return data;
       }

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

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
public class ClassC {
       @XmlElement
       private ClassA classA;
       @XmlElement
       private ClassB classB;

       public ClassA getClassA() {
              return classA;
       }

       public void setClassA(ClassA classA) {
              this.classA = classA;
       }

       public ClassB getClassB() {
              return classB;
       }

       public ClassB setClassB(ClassB classB) {
              this.classB = classB;
       }
}

此映射对我有用。

You can use this method:

public interface Data {}

@XmlTransient
public abstract class A {
       private Data data;

       public Data getData(){
              return data;
       }

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

@XmlAccessorType(XmlAccessType.NONE)
public class ClassA extends A {

       // DataA implements Data
       @XmlElement(type=DataA.class)
       public Data getData(){
              return super.getData();
       }

       public void setData(DataA data){
              super.setData(data);
       }
}

@XmlAccessorType(XmlAccessType.NONE)
public class ClassB extends A {
       // DataB implements Data
       private DataB data;

       @XmlElement(type=DataB.class)
       public DataA getData(){
              return data;
       }

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

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
public class ClassC {
       @XmlElement
       private ClassA classA;
       @XmlElement
       private ClassB classB;

       public ClassA getClassA() {
              return classA;
       }

       public void setClassA(ClassA classA) {
              this.classA = classA;
       }

       public ClassB getClassB() {
              return classB;
       }

       public ClassB setClassB(ClassB classB) {
              this.classB = classB;
       }
}

this mapping worked for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文