title: Serializing with JAXB and the Any
body: <p>I have a schema that defines the following type:</p>
  
  <pre><code>&lt;xsd:complexType name="Payload"&gt;
     &lt;xsd:sequence&gt;
        &lt;xsd:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax"/&gt;
     &lt;/xsd:sequence&gt;
  &lt;/xsd:complexType&gt;
  </code></pre>
  
  <p>And that creates an object like so:</p>
  
  <pre><code>@XmlAccessorType(XmlAccessType.FIELD)
  @XmlType(name = "Payload", propOrder = {
      "any"
  })
  public class Payload {
  
      @XmlAnyElement(lax = true)
      protected List&lt;Object&gt; any;
  }
  </code></pre>
  
  <p>Now I try adding another generated JAXB object to that Payload doing something like this:</p>
  
  <pre><code>Class payloadClass = ...;
  JAXBContext context = JAXBContext.newInstance( WrapperRequest.class, payloadClass);
  ...
  marshaller.marshal( wrappedRequest );
  </code></pre>
  
  <p>But I get a terrible exception that looks like it'll never work so I decide to serialize the payload object to XML first then add that as a string in the payload.</p>
  
  <pre><code>StringWriter writer = new StringWriter();
  JAXBContext context = JAXBContext.newInstance( sdoRequest.getClass() );
  Marshaller marshaller = context.createMarshaller();
  marshaller.marshal(new JAXBElement(new QName("uri", sdoRequest.getClass().getSimpleName()), sdoRequest.getClass(), sdoRequest), writer);
  payload.getAny().add( writer.toString() );
  </code></pre>
  
  <p>And this blows up with an exception saying "java.lang.String" does not contain an @XmlRootElement.</p>
  
  <p>So how will the use of xs:any ever work with JAXB?  Nothing seems to want to work because JAXB turns the Payload into Object, and it won't serialize just anything in Object.  This is all inside Axis2 as well so it's been very challenging to get to this point.</p>