Support JAXBElement in Jaxb2XmlEncoder

This commit introduces support for JAXBElements in the Jaxb2XmlEncoder.

Closes gh-30552
This commit is contained in:
Arjen Poutsma
2023-06-08 15:29:56 +02:00
parent 2f78b42133
commit d7970e4ab8
2 changed files with 27 additions and 2 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.function.Function;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.MarshalException;
import jakarta.xml.bind.Marshaller;
@@ -121,7 +122,7 @@ public class Jaxb2XmlEncoder extends AbstractSingleValueEncoder<Object> {
DataBuffer buffer = bufferFactory.allocateBuffer(1024);
try {
OutputStream outputStream = buffer.asOutputStream();
Class<?> clazz = ClassUtils.getUserClass(value);
Class<?> clazz = getMarshallerType(value);
Marshaller marshaller = initMarshaller(clazz);
marshaller.marshal(value, outputStream);
release = false;
@@ -140,6 +141,15 @@ public class Jaxb2XmlEncoder extends AbstractSingleValueEncoder<Object> {
}
}
private static Class<?> getMarshallerType(Object value) {
if (value instanceof JAXBElement<?> jaxbElement) {
return jaxbElement.getDeclaredType();
}
else {
return ClassUtils.getUserClass(value);
}
}
private Marshaller initMarshaller(Class<?> clazz) throws CodecException, JAXBException {
Marshaller marshaller = this.jaxbContexts.createMarshaller(clazz);
marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());