如何在Scala中将JSON转换为类型 [英] How to convert JSON to a type in Scala

查看:129
本文介绍了如何在Scala中将JSON转换为类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我从Twitter收到了JSON文本.然后,我想将此文本转换为Scala中的本机对象.是否有标准方法可以做到这一点?我也在使用Play 2

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 Play 2

这就是我所拥有的

import scala.io.Source.{fromInputStream}
import java.net._

val url = new URL("https://api.twitter.com/1/trends/1.json")
val content = fromInputStream( url.openStream ).getLines.mkString("\n")
val json = Json.parse(content)
val a = (json \ "trends" )
Ok(a(0))

我想从JSON获取所有趋势名称

I want to get all the trends name from the JSON

推荐答案

我个人更喜欢lift-json,但是使用

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)

是的,看起来不错.

这篇关于如何在Scala中将JSON转换为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆