2017-06-14 10 views
0

My Jsonはオブジェクトのリストです。私は最初のものを取得したいが、Anyは、それが困難にされています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

結果(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)) 
関連する問題