I have run into a few issues in my Java 1.8 application when trying to use JAXB to marshal my Java object into an XML string. The first issue was that by default marshalling escapes < and > so when i was trying to wrap some fields in
<![CDATA[ my-field-value ]]>
it was being turned into
<![CDATA[ my-field-value ]]>
Which breaks functionality of using CDATA in the first place. I used a custom character handler according to some comments from How to prevent JAXB escaping a string. Everything is working for me now but i have heard that im not supposed to use com.sun.xml.internal.* packages and currently I am doing so like this (notice the use of internal):
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
JAXBContext jc = JAXBContext.newInstance(MyClass.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(
"com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler",
new MyCustomCharacterHandler());
return marshaller;
Where MyCustomCharacterHandler is declared like so (note the use of internal):
import com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler;
public class XmlCdataCharacterHandler implements CharacterEscapeHandler {
...
}
This combination is working fine for me but when modifying my code to get rid of .internal.* like so using this dependency:
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.7</version>
</dependency>
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
public class XmlCdataCharacterHandler implements CharacterEscapeHandler {
...
}
JAXBContext jc = JAXBContext.newInstance(PrintPack.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(
"com.sun.xml.bind.marshaller.CharacterEscapeHandler",
new MyCustomCharacterHandler());
return marshaller;
My server will no longer start and is getting a JAXBException with the following message:
name: com.sun.xml.bind.marshaller.CharacterEscapeHandler value: com.fmrco.research.search.handlers.MyCustomCharacterHandler@1f3d4305
Which makes me think that my custom handler which implements the CharacterEscapeHandler is no longer being used correctly. Does anyone know how to fix this so i can keep this implementation while avoiding com.sun.xml.internal.* packages? Is there a better/newer way to turn a java class into an XML string? Seems like I should not be stuck on this for as long as I have been. Thank you!