如何从Any获得第一个元素

时间:2017-06-14 05:59:11

标签: json scala

我的Json是一个对象列表。我想得到第一个,但是Any让它变得困难:

scala> import scala.util.parsing.json._
import scala.util.parsing.json._

scala> val str ="""
     | [
     |   {
     |     "UserName": "user1",
     |     "Tags": "one, two, three"
     |   },
     |   {
     |     "UserName": "user2",
     |     "Tags": "one, two, three"
     |   }
     | ]""".stripMargin
str: String =
"
 [
   {
     "UserName": "user1",
     "Tags": "one, two, three"
   },
   {
     "UserName": "user2",
     "Tags": "one, two, three"
   }
 ]"

scala> val parsed = JSON.parseFull(str)
parsed: Option[Any] = Some(List(Map(UserName -> user1, Tags -> one, two, three), Map(UserName -> user2, Tags -> one, two, three)))

scala> parsed.getOrElse(0)
res0: Any = List(Map(UserName -> user1, Tags -> one, two, three), Map(UserName -> user2, Tags -> one, two, three))

scala> parsed.getOrElse(0)(0)
<console>:13: error: Any does not take parameters
              parsed.getOrElse(0)(0)

我如何获得第一个元素?

1 个答案:

答案 0 :(得分:1)

您需要将结果(Option[Any])与List[Map[String, String]]进行模式匹配。

1)模式匹配示例,

scala> val parsed = JSON.parseFull("""[{"UserName":"user1","Tags":"one, two, three"},{"UserName":"user2","Tags":"one, two, three"}]""")

scala> parsed.map(users => users match { case  usersList : List[Map[String, String]] => usersList(0) case _ => Option.empty })
res8: Option[Equals] = Some(Map(UserName -> user1, Tags -> one, two, three))

更好的模式匹配,

scala> parsed.map(_ match { case  head :: tail => head case _ => Option.empty })
res13: Option[Any] = Some(Map(UserName -> user1, Tags -> one, two, three))

2)否则你可以转换结果(Option[Any])但不推荐(因为强制转换可能抛出ClassCastException),

scala> parsed.map(_.asInstanceOf[List[Map[String, String]]](0))
res10: Option[Map[String,String]] = Some(Map(UserName -> user1, Tags -> one, two, three))