如何在 Spray 中解组案例列表 class
How to unmarshall a list of case class in Spray
第一次使用 Spray 的用户无法在任何地方找到任何合适的示例。我希望解组包含 List[Person]
.
的 XML API 响应
说 case class Person(name: String, age: Int)
。解组器应生成适当的 List[Person]
.
Spray 有一个默认值 NodeSeqUnmarshaller
但我不知道如何正确链接事物,将不胜感激任何指点。
我必须在我的应用程序中解决这个问题。以下是一些基于您的示例案例 class 的代码,您可能会发现它们对您有所帮助。
我的方法使用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))
}
}
第一次使用 Spray 的用户无法在任何地方找到任何合适的示例。我希望解组包含 List[Person]
.
说 case class Person(name: String, age: Int)
。解组器应生成适当的 List[Person]
.
Spray 有一个默认值 NodeSeqUnmarshaller
但我不知道如何正确链接事物,将不胜感激任何指点。
我必须在我的应用程序中解决这个问题。以下是一些基于您的示例案例 class 的代码,您可能会发现它们对您有所帮助。
我的方法使用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))
}
}