Jaxb marshalling, ignore nillable

I have a class with variables with nillable = true annotation and I don't want them to be displayed in xml. The class is generated from xsd, which cannot be changed.

Example: A class that looks something like this:

public class Hi {
    ...
    @XmlElement(name = "hello", nillable = true)
    protected Long hello;
    ...
}

The object is sorted using the JAXBContext marshaller. The generated xml turns into:

...
<hello xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
...

The Hi class is generated from xsd, which cannot be changed. My question is, is there a way to make the marshaller ignore the nillable argument and not output anything in xml if "hello" is null?

+4
source share
2 answers

Nicolas Filotto , xmlstreamwriter (DelegateXMLStreamWriter ):

. nillable , , . , , nillable, .

public class XMLExportStreamWriter extends DelegateXMLStreamWriter {

private Set<String> nillableElements;
private final Stack<String> path = new Stack<>();

private boolean nillable;
private boolean notNull;

private String localName;
private String namespaceURI;
private String prefix;

public XMLExportStreamWriter(XMLStreamWriter delegate) throws XMLStreamException {
    super.setDelegate(delegate);
}

public void setNillableElements(Set<String> nillableElements) {
    this.nillableElements = nillableElements;
}

@Override
public void writeStartElement(String localName) throws XMLStreamException {
    if (!isNillable(localName)) {
        super.writeStartElement(localName);
    } else {
        setElementArgs(null, localName, null);
    }
}

@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
    if (!isNillable(localName)) {
        super.writeStartElement(namespaceURI, localName);
    } else {
        setElementArgs(null, localName, namespaceURI);
    }
}

@Override
public void writeStartElement(String prefix, String localName, String namespaceURI)
    throws XMLStreamException {
    if (!isNillable(localName)) {
        super.writeStartElement(prefix, localName, namespaceURI);
    } else {
        setElementArgs(prefix, localName, namespaceURI);
    }
}

@Override
public void writeEndElement() throws XMLStreamException {
    if (!this.nillable || this.notNull) {
        super.writeEndElement();
    }
    this.path.pop();
    if (this.nillable) {
        this.nillable = this.nillableElements.contains(toPath());
    }
}

@Override
public void writeCharacters(String text) throws XMLStreamException {
    if (this.nillable) {
        if (text != null) {
            this.notNull = true;
            forceStartElement();
            super.writeCharacters(text);
        }
    } else {
        super.writeCharacters(text);
    }
}

@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
    if (this.nillable) {
        if (text != null) {
            this.notNull = true;
            forceStartElement();
            super.writeCharacters(text, start, len);
        }
    } else {
        super.writeCharacters(text, start, len);
    }
}

@Override
public void writeAttribute(String localName, String value) throws XMLStreamException {
    if (!this.nillable) {
        super.writeAttribute(localName, value);
    }
}

@Override
public void writeAttribute(String namespaceURI, String localName, String value)
    throws XMLStreamException {
    if (!this.nillable) {
        super.writeAttribute(namespaceURI, localName, value);
    }
}

@Override
public void writeAttribute(String prefix, String namespaceURI, String localName, String value)
    throws XMLStreamException {
    if (!this.nillable) {
        super.writeAttribute(prefix, namespaceURI, localName, value);
    }
}

@Override
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
    if (!this.nillable) {
        super.writeNamespace(prefix, namespaceURI);
    }
}

private void forceStartElement() throws XMLStreamException {
    if (this.prefix != null) {
        super.writeStartElement(this.prefix, this.localName, this.namespaceURI);
    } else if (this.namespaceURI != null) {
        super.writeStartElement(this.namespaceURI, this.localName);
    } else {
        super.writeStartElement(this.localName);
    }
}

private boolean isNillable(String localName) {
    this.notNull = false;
    this.path.push(localName);
    this.nillable = this.nillableElements.contains(toPath());
    return this.nillable;
}

private void setElementArgs(String prefix, String localName, String namespaceURI) {
    this.prefix = prefix;
    this.localName = localName;
    this.namespaceURI = namespaceURI;
}

private String toPath() {
    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String element : this.path) {
        if (first) {
            first = false;
        } else {
            sb.append('/');
        }
        sb.append(element);
    }
    return sb.toString();
}

}

:

private static Set<String> pathsToSkip(Class<?> clazz) {
    // Make sure that the class is annotated with XmlRootElement
    XmlRootElement rootElement = clazz.getAnnotation(XmlRootElement.class);
    if (rootElement == null) {
        throw new IllegalArgumentException("XmlRootElement is missing");
    }
    // Create the root name from the annotation or from the class name
    String rootName = ("##default".equals(rootElement.name()) ?
    clazz.getSimpleName().substring(0, 1).toLowerCase() + clazz.getSimpleName().substring(1) :
    rootElement.name());
    // Set that will contain all the paths
    Set<String> pathsToSkip = new HashSet<>();        
    addPathsToSkip(rootName, clazz, pathsToSkip);
    return pathsToSkip;
}

private static void addPathsToSkip(String parentPath, Class<?> clazz, 
                               Set<String> pathsToSkip) {
    // Iterate over all the fields
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        XmlElement xmlElement = field.getAnnotation(XmlElement.class);
        if (xmlElement != null) {
            // Create the name of the element from the annotation or the field name
            String elementName = ("##default".equals(xmlElement.name()) ?
            field.getName() :
            xmlElement.name());
            String path = parentPath + "/" + elementName;
            if (xmlElement.nillable()) {
                // It is nillable so we add it to the paths to skip
                pathsToSkip.add(path);
            } else {
                // It is not nillable so we check the fields corresponding 
                // to the field type

                // If it a collection we need to get the generic type
                if (Collection.class.isAssignableFrom(field.getType())) {
                    ParameterizedType fieldGenericType = (ParameterizedType) field
                        .getGenericType();
                    Class<?> fieldGenericTypeClass = (Class<?>) fieldGenericType
                        .getActualTypeArguments()[0];
                    addPathsToSkip(path, fieldGenericTypeClass, pathsToSkip);
                } else {
                    addPathsToSkip(path, field.getType(), pathsToSkip);
                }
            }
        }
    }
}

- :

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(filePath)));
XMLExportStreamWriter exportStreamWriter = new XMLExportStreamWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(
                bufferedWriter);
exportStreamWriter.setNillableElements(getNillablePaths(MyClass.class));
0

- decorator XMLStreamWriter .

( , ), , , :

public class FilteredXMLStreamWriter implements XMLStreamWriter {
    private final XMLStreamWriter writer;
    private final Set<String> pathsToSkip;
    private final Stack<String> path = new Stack<>();
    private boolean ignore;

    public FilteredXMLStreamWriter(XMLStreamWriter writer, Set<String> pathsToSkip) {
        this.writer = writer;
        this.pathsToSkip = pathsToSkip;
    }

    /**
     * Build the current path from the Stack
     */
    private String toPath() {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (String element : path) {
            if (first) {
                first = false;
            } else {
                sb.append('/');
            }
            sb.append(element);
        }
        return sb.toString();
    }

    public void writeStartElement(String prefix, String localName, String namespaceURI) 
        throws XMLStreamException {
        // Add the current
        path.push(localName);
        if (!ignore) {
            this.ignore = pathsToSkip.contains(toPath());
            if (!ignore) {
                this.writer.writeStartElement(prefix, localName, namespaceURI);
            }
        }
    }
    ...

    public void writeEndElement() throws XMLStreamException {
        if (ignore) {
            this.ignore = !pathsToSkip.contains(toPath());
        } else {
            this.writer.writeEndElement();
        }
        path.pop();
    }
    ...

    public void writeCharacters(String text) throws XMLStreamException {
        if (!ignore) {
            this.writer.writeCharacters(text);
        }
    }

    public void writeCharacters(char[] text, int start, int len) 
        throws XMLStreamException {
        if (!ignore) {
            this.writer.writeCharacters(text, start, len);
        }
    }

    ...
}

:

private static Set<String> pathsToSkip(Class<?> clazz) {
    // Make sure that the class is annotated with XmlRootElement
    XmlRootElement rootElement = clazz.getAnnotation(XmlRootElement.class);
    if (rootElement == null) {
        throw new IllegalArgumentException("XmlRootElement is missing");
    }
    // Create the root name from the annotation or from the class name
    String rootName = ("##default".equals(rootElement.name()) ?
        clazz.getSimpleName().substring(0, 1).toLowerCase() + clazz.getSimpleName().substring(1) :
        rootElement.name());
    // Set that will contain all the paths
    Set<String> pathsToSkip = new HashSet<>();        
    addPathsToSkip(rootName, clazz, pathsToSkip);
    return pathsToSkip;
}

private static void addPathsToSkip(String parentPath, Class<?> clazz, 
                                   Set<String> pathsToSkip) {
    // Iterate over all the fields
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        XmlElement xmlElement = field.getAnnotation(XmlElement.class);
        if (xmlElement != null) {
            // Create the name of the element from the annotation or the field name
            String elementName = ("##default".equals(xmlElement.name()) ?
                field.getName() :
                xmlElement.name());
            String path = parentPath + "/" + elementName;
            if (xmlElement.nillable()) {
                // It is nillable so we add it to the paths to skip
                pathsToSkip.add(path);
            } else {
                // It is not nillable so we check the fields corresponding 
                // to the field type
                addPathsToSkip(path, field.getType(), pathsToSkip);
            }
        }
    }
}

:

marshaller.marshal(
    myObject, 
    new FilteredXMLStreamWriter(
        XMLOutputFactory.newInstance().createXMLStreamWriter(sw),
        pathsToSkip(Hi.class)
    )
);
+2

Source: https://habr.com/ru/post/1652835/


All Articles