Search code examples
xmlscalaakka-httpscala-xml

Scala: akka http unmarshal xml strings to case classes


I have a simple XML response from third-party API.

Let's say it looks like

<items>
    <item name="name1"/>
    <item name="name2"/>
    <item name="name3"/>
 </items>

Having a case classes

case class Items(children: List[Item]) 
case class Item(name: String)

How can I write unmarshaller to use implicitly which will work with code like this:

Unmarshal(myXmlString).to[Items].map ...

Or better

Unmarshal(myXmlString).to[List[Item]].map ...

Can I do it without defining any unmarshal functions which explicitly access XML? Data I already have looks declarative enough have unmarshalling without additional boilerplate.


Solution

  • scala-xml doesn't provide any deserializer to hydrate your custom objects. If the requirement is simple as mentioned in the sample example, you can try something like this below:

        scala> val itemsString = "<items><item name='name1'/><item name='name2'/><item name='name3'/></items>"   
        scala> val itemsXml = scala.xml.XML.loadString(itemsString)                                              
        scala> val items = Items(( itemsXml \\  "@name").toList.map(( x=> Item(x.toString)) ))                               │