2

第一次喷雾用户未能在任何地方找到任何合适的例子。我正在寻找解组包含List[Person].

case class Person(name: String, age: Int)。解组器应生成适当的List[Person].

Spray有一个默认值NodeSeqUnmarshaller,但我无法弄清楚如何正确链接事物,将不胜感激任何指针。

4

1 回答 1

5

我必须在我的应用程序中解决这个问题。以下是一些基于您的示例案例类的代码,您可能会发现它们会有所帮助。

我的方法使用这里Unmarshaller.delegate讨论的。

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))
  }
}
于 2015-02-23T23:34:22.523 回答