Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.xml.bind.PropertyException when jaxb marshalling

I am trying to marshal a list of objects into xml. Below is the method:

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;
    }
}

When I call m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() I get the following error:

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)

Now if I use the Internal class: com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper;

instead, it works. However this project is to be built using maven and it complains when you have a dependency on an internal class. Also it's a bad idea to use internal classes, or so I'm told.

How can I fix this?

like image 797
bunion92 Avatar asked May 11 '17 09:05

bunion92


1 Answers

Option 1: Use the annotations in package-info.java file instead of NamespacePrefixMapper Class:

@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;

Option 2: In maven I added the following build dependency:

<!-- 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>

This enables you to use com.sun.xml.bind.marshaller.NamespacePrefixMapper.

like image 193
gifpif Avatar answered Nov 02 '22 19:11

gifpif