Akka HTTP’s marshalling and unmarshalling infrastructure makes it rather easy to seamlessly support specific wire representations of your data objects, like JSON, XML or even binary encodings.
Akka HTTP does not currently provide a Java API for XML support. If you need to produce and consume XML, you can write a custom marshaller using Jackson, which is also the library used for providing JSON support.
sourceimport java.io.IOException;import java.util.List;import java.util.Arrays;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;import com.fasterxml.jackson.dataformat.xml.XmlMapper;import akka.http.javadsl.model.*;import akka.http.javadsl.marshalling.Marshaller;import akka.http.javadsl.unmarshalling.Unmarshaller;publicclassJacksonXmlSupport{privatestaticfinalObjectMapper DEFAULT_XML_MAPPER =newXmlMapper().enable(SerializationFeature.WRAP_ROOT_VALUE);privatestaticfinalList<MediaType> XML_MEDIA_TYPES =Arrays.asList(MediaTypes.APPLICATION_XML,MediaTypes.TEXT_XML);publicstatic<T>Marshaller<T,RequestEntity> marshaller(){returnMarshaller.wrapEntity(
u -> toXML(DEFAULT_XML_MAPPER, u),Marshaller.stringToEntity(),MediaTypes.APPLICATION_XML
);}publicstatic<T>Unmarshaller<HttpEntity, T> unmarshaller(Class<T> expectedType){returnUnmarshaller.forMediaTypes(XML_MEDIA_TYPES,Unmarshaller.entityToString()).thenApply(xml -> fromXML(DEFAULT_XML_MAPPER, xml, expectedType));}privatestatic<T>String toXML(ObjectMapper mapper, T object){try{return mapper.writeValueAsString(object);}catch(IOException e){thrownewIllegalArgumentException("Cannot marshal to XML: "+object, e);}}privatestatic<T> T fromXML(ObjectMapper mapper,String xml,Class<T> expectedType){try{return mapper.readerFor(expectedType).readValue(xml);}catch(IOException e){thrownewIllegalArgumentException("Cannot unmarshal XML as "+ expectedType.getSimpleName(), e);}}}
The custom XML (un)marshalling code shown above requires that you depend on the jackson-dataformat-xml library.
The Akka dependencies are available from Akka’s library repository. To access them there, you need to configure the URL for this repository.
Once you have done this (un)marshalling between XML and NodeSeq instances should work nicely and transparently, by either using import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ or mixing in the akka.http.scaladsl.marshallers.xml.ScalaXmlSupport trait.