【问题标题】:How to unmarshall a list of case class in Spray如何在Spray中解组案例类列表
【发布时间】:2015-02-23 16:31:03
【问题描述】:

第一次 Spray 用户未能在任何地方找到任何合适的示例。我希望解组包含 List[Person] 的 XML API 响应。

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

Spray 有一个默认的 NodeSeqUnmarshaller,但我不知道如何正确链接,如果有任何指点,将不胜感激。

【问题讨论】:

  • 您是否为您的案例类定义了 JsonFormat,定义如下:github.com/spray/… ?
  • @lpiepiora 不确定这与 XML 解组有什么关系。
  • 啊,对不起,无论出于何种原因,我认为你在谈论 JSON,忘了它
  • @flavian,达里尔的回答正确吗?你忘记接受了吗?

标签: xml scala spray spray-client


【解决方案1】:

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

我的方法使用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))
  }
}

【讨论】:

  • 感谢您,同时找到了委托方法。
  • @flavian - 如果您同意这是解决问题的方法,请“接受”我的回答。谢谢。
猜你喜欢
  • 2023-03-10
  • 2018-10-23
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多