简体   繁体   中英

@XmlSeeAlso doesn't work for the same root node

I'm trying to implement inheritance with @XmlSeeAlso annotation. Everything works as expected when using different root node names for subclasses. But with the same root names Unmarshaller always choses the last class from the XmlSeeAlso list despite of the content. It's impossible to change root names. Is where any way to make Unmarshaller to chose class correctly by content?

import java.io.ByteArrayInputStream;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.jaxb.Jaxb2Marshaller;

public class Test {
  public static void main(String[] args) {
    Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
    unmarshaller.setClassesToBeBound(Parent.class);
    System.out.println(unmarshaller.unmarshal(new StreamSource(
        new ByteArrayInputStream("<value><a>AAA</a><b>BBB</b></value>"
            .getBytes()))));
    System.out.println(unmarshaller.unmarshal(new StreamSource(
        new ByteArrayInputStream("<value><c>CCC</c><d>DDD</d></value>"
            .getBytes()))));
  }

  @XmlSeeAlso({ ChildAB.class, ChildCD.class })
  public static abstract class Parent {
  }

  @XmlRootElement(name = "value")
  public static class ChildAB {
    @XmlElement(name = "a")
    private String a;
    @XmlElement(name = "b")
    private String b;

    @Override
    public String toString() {
      return "ChildAB[" + a + "; " + b + "]";
    }
  }

  @XmlRootElement(name = "value")
  public static class ChildCD {
    @XmlElement(name = "c")
    private String c;
    @XmlElement(name = "d")
    private String d;

    @Override
    public String toString() {
      return "ChildCD[" + c + "; " + d + "]";
    }
  }
}

Output:

ChildCD[null; null]
ChildCD[CCC; DDD]

Why your class ChildAB and ChildCD are static? Also ChildAB and ChildCD should implement/extend your Parent class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM