Apache Pekko 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.
Apache Pekko 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 org.apache.pekko.http.javadsl.model.*;import org.apache.pekko.http.javadsl.marshalling.Marshaller;import org.apache.pekko.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.
Once you have done this (un)marshalling between XML and NodeSeq instances should work nicely and transparently, by either using import org.apache.pekko.http.scaladsl.marshallers.xml.ScalaXmlSupport._ or mixing in the org.apache.pekko.http.scaladsl.marshallers.xml.ScalaXmlSupport trait.