jaxb编组时的javax.xml.bind.PropertyException

我试图将对象列表编组为xml.

以下是方法:

import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
import javax.xml.bind.Marshaller;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

public class ItemMarshaller
{
    public String marshallItems(final List<Items> items)
    {
        try
        {
            final JAXBContext context = JAXBContext.newInstance("com.project.jaxb.items");
            final Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper()
            {
                @Override
                public String getPreferredPrefix(String uri, String suggestion, boolean requirePrefix)
                {
                    return "";
                }
            });

            final StringWriter writer = new StringWriter();
            m.marshal(items, writer);

            return writer.toString();
        }
        catch (final JAXBException e)
        {
            ErrorLogger.LOGGER.error("Marshalling failed.", e); //$NON-NLS-1$
        }

        return null;
    }
}

当我调用m.setProperty(“com.sun.xml.bind.namespacePrefixMapper”,新的NamespacePrefixMapper()时,我收到以下错误:

javax.xml.bind.PropertyException: name: com.sun.xml.bind.namespacePrefixMapper value: com.project.ItemMarshaller$1@eb6e072
at javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(AbstractMarshallerImpl.java:358)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty(MarshallerImpl.java:527)

现在如果我使用Internal类:
com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper;

相反,它的工作原理.但是,这个项目是使用maven构建的,当你依赖内部类时会抱怨它.使用内部类也是一个坏主意,或者我被告知.

我怎样才能解决这个问题?

最佳答案 选项1:

使用package-info.java文件中的注释而不是NamespacePrefixMapper类:

@javax.xml.bind.annotation.XmlSchema(
        namespace = "http://www.example.com/schema/impl", 
        elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
        xmlns={@XmlNs(prefix="ns0", namespaceURI="http://www.example.com/schema/impl")}
    )
package com.abc.schema.impl;

选项2:
在maven中我添加了以下构建依赖项:

<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2.4-1</version>
</dependency>

这使您可以在您使用的任何Java版本上使用com.sun.xml.bind.marshaller.NamespacePrefixMapper.

点赞