如何模式匹配JsStrings的JsArray

时间:2019-06-28 12:28:39

标签: scala spray-json

例如,我有一个简单的作者的JSON:

{
  "name": "string",
  "articles": [
    "string",
    "string",
    "string"
  ]
}

我正在定义Json的阅读格式:

implicit object authorFormat extends RootJsonFormat[Author] {
  override def write(a: Author) = ???

  override def read(json: JsValue) = json.asJsObject.getFields("name", "articles") match {
    case Seq(JsString(name), JsArray(articles)) => ... //Build author
  }
}

此模式匹配确保"articles"是一个数组(JsValues)。但这不能保证"articles"是字符串数组。如何解决?

1 个答案:

答案 0 :(得分:1)

尝试像这样将articles反序列化为List[String]

articles.map(_.convertTo[String]).toList

如果jsonFormat2不是选项。这是一个有效的例子

import spray.json._
import DefaultJsonProtocol._

object MyApp extends App {
  case class Author(name: String, articles: List[String])

  implicit object authorFormat extends RootJsonFormat[Author] {
    override def write(a: Author) = ???

    override def read(json: JsValue) = json.asJsObject.getFields("name", "articles") match {
      case Seq(JsString(name), JsArray(articles)) => Author(name, articles.map(_.convertTo[String]).toList)
    }
  }

  val raw =
    """
      |{
      |  "name": "string",
      |  "articles": [
      |    "string,
      |    "string",
      |    "string"
      |  ]
      |}
    """.stripMargin



  val json = raw.parseJson
  val author = json.convertTo[Author]
  println(author)
}

输出

Author(string,List(string, string, string))

如果articles包含这样的非字符串,则

  val raw =
    """
      |{
      |  "name": "string",
      |  "articles": [
      |    1,
      |    "string",
      |    "string"
      |  ]
      |}
    """.stripMargin

我们得到错误

Exception in thread "main" spray.json.DeserializationException: Expected String as JsString, but got 1