2015-02-23 40 views
2

第一次噴霧用戶無法在此處找到適當的示例。我期待解除包含List[Person]的XML API響應。如何解開噴霧中的案例類別列表

case class Person(name: String, age: Int)。解組員應該產生適當的List[Person]

噴霧有一個默認的NodeSeqUnmarshaller,但我不知道如何正確鏈接的東西,將不勝感激任何指針。

+0

你有一個定義爲JsonFormat您的案件類,如下定義:https://github.com/spray/spray-json#providing-jsonformats-for-case-classes? – lpiepiora 2015-02-23 16:36:19

+0

@lpipiora不確定與XML解組有什麼關係。 – flavian 2015-02-23 16:45:00

+0

啊,對不起因爲什麼原因,我以爲你說的是​​JSON,忘了它 – lpiepiora 2015-02-23 16:52:55

回答

5

我不得不在我的應用程序中解決這個問題。以下是一些基於您的示例案例類的代碼,您可能會發現這些代碼很有幫助。

我的方法使用Unmarshaller.delegate,如here所述。

import scala.xml.Node 
import scala.xml.NodeSeq 
import spray.httpx.unmarshalling._ 
import spray.httpx.unmarshalling.Unmarshaller._ 

case class Person(name: String, age: Int) 

object Person { 
    def fromXml(node: Node): Person = { 
    // add code here to instantiate a Person from a Node 
    } 
} 

case class PersonSeq(persons: Seq[Person]) 

object PersonSeq { 
    implicit val PersonSeqUnmarshaller: Unmarshaller[PersonSeq] = Unmarshaller.delegate[NodeSeq, PersonSeq](MediaTypes.`text/xml`, MediaTypes.`application/xml`) { 
    // Obviously, you'll need to change this function, but it should 
    // give you an idea of how to proceed. 
    nodeSeq => 
     val persons: NodeSeq = nodeSeq \ "PersonList" \ "Person" 
     PersonSeq(persons.map(node => Person.fromXml(node)) 
    } 
} 
+0

謝謝你,同時找到委託方法。 – flavian 2015-02-23 23:42:37

+1

@flavian - 如果您同意這是解決問題的方法,請「接受」我的回答。謝謝。 – 2015-02-23 23:52:00