How to convert JSON to a type in Scala

后端 未结 5 1816
野性不改
野性不改 2021-02-19 04:06

My problem is I receive an JSON text from say, twitter. Then I want to convert this text to an native object in scala. Is there a standard method to do this? I\'m also using Pla

5条回答
  •  暖寄归人
    2021-02-19 04:19

    I personally prefer lift-json, but it's pretty easy to do this with Play's JSON library:

    import play.api.libs.json._
    import scala.io.Source
    
    case class Trend(name: String, url: String)
    
    implicit object TrendReads extends Reads[Trend] {
      def reads(json: JsValue) = Trend(
        (json \ "name").as[String],
        (json \ "url").as[String]
      )
    }
    
    val url = new java.net.URL("https://api.twitter.com/1/trends/1.json")
    val content = Source.fromInputStream(url.openStream).getLines.mkString("\n")
    val trends = Json.parse(content) match {
      case JsArray(Seq(t)) => Some((t \ "trends").as[Seq[Trend]])
      case _ => None
    }
    

    Right now this produces the following:

    scala> trends.foreach(_.foreach(println))
    Trend(#TrueFactsAboutMe,http://twitter.com/search/?q=%23TrueFactsAboutMe)
    Trend(#200mFinal,http://twitter.com/search/?q=%23200mFinal)
    Trend(Jamaica 1,2,3,http://twitter.com/search/?q=%22Jamaica%201,2,3%22)
    Trend(#DontComeToMyHouse,http://twitter.com/search/?q=%23DontComeToMyHouse)
    Trend(Lauren Cheney,http://twitter.com/search/?q=%22Lauren%20Cheney%22)
    Trend(Silver & Bronze,http://twitter.com/search/?q=%22Silver%20&%20Bronze%22)
    Trend(Jammer Martina,http://twitter.com/search/?q=%22Jammer%20Martina%22)
    Trend(Japan 2-0,http://twitter.com/search/?q=%22Japan%202-0%22)
    Trend(Prata e Bronze,http://twitter.com/search/?q=%22Prata%20e%20Bronze%22)
    Trend(Final 200m,http://twitter.com/search/?q=%22Final%20200m%22)
    

    So yeah, looks about right.

提交回复
热议问题