fla*_*ian 2 xml scala spray spray-client
第一次喷涂用户无法在任何地方找到任何适当的示例.我想要解组包含一个的XML API响应List[Person].
说case class Person(name: String, age: Int).unmarshaller应该产生适当的List[Person].
Spray有一个默认值,NodeSeqUnmarshaller但我无法弄清楚如何正确地连接东西,会感激任何指针.
我必须在我的应用程序中解决这个问题.以下是一些基于您的示例案例类的代码,您可能会发现这些代码很有帮助.
我的方法是使用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))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
943 次 |
| 最近记录: |