XmlAdapter for base64Binary results in String

我是研究僧i 提交于 2020-01-24 11:10:07

问题


I've an XSD file containing this:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:extensionBindingPrefixes="xjc"
elementFormDefault="qualified"
targetNamespace="http://example.org/">

<xsd:complexType name="Certificate">
    <xsd:sequence>
        <xsd:element name="certificate" type="xsd:base64Binary">
            <xsd:annotation>
                <xsd:appinfo>
                    <xjc:javaType name="java.security.cert.X509Certificate" adapter="adapters.X509CertificateAdapter" />
                </xsd:appinfo>
            </xsd:annotation>
        </xsd:element>
    </xsd:sequence>
</xsd:complexType>

</xsd:schema>

and when I generate java code with xjc, it produces this:

public class Certificate {

    @XmlElement(required = true, type = String.class)
    @XmlJavaTypeAdapter(X509CertificateAdapter.class)
    @XmlSchemaType(name = "base64Binary")
    protected X509Certificate certificate;

    ....
}

and the adapter works fine.

My question is why @XmlElement(required = true, type = String.class) ? Why type = String.class and not byte[]?


回答1:


For the following:

@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(X509CertificateAdapter.class)
@XmlSchemaType(name = "base64Binary")
protected X509Certificate certificate;

There are a few things to note:

  1. The type setting on @XmlElement is redundant since the X509CertificateAdapter already specifies that for the purposes of marshalling & unmarshalling it is going to convert X508Certificate to/from a String.
  2. The X509CertificateAdapter converts to/from a String instead of a byte[] most likely for the purposes of performance, as a conversion to a byte[] would cause JAXB to do an additional conversion to String to render it correctly in the XML.
  3. The @XmlSchemaType annotation is used to ensure that when an XML Schema is generated that the node type shows up as base64Binary and not string.



回答2:


This class "adapters.X509CertificateAdapter" declares two methods:

public X509Certificate unmarshal(String certificateBase64String) throws Exception;
public String marshal(X509Certificate certificate) throws Exception;

The first declaration needs of a String to unmarshal some X509Certificate. In this way you can use directly a X509Certificate.

I hope I've given you all the answers about your question



来源:https://stackoverflow.com/questions/24903790/xmladapter-for-base64binary-results-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!