Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON to a type in Scala

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

Here is what I have

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))

I want to get all the trends name from the JSON

like image 383
Athiwat Chunlakhan Avatar asked Aug 09 '12 18:08

Athiwat Chunlakhan


People also ask

How to convert JSON string to Scala object?

Use the Lift-JSON library to convert a JSON string to an instance of a case class. This is referred to as deserializing the string into an object. Once you have a JValue object, use its extract method to create a MailServer object: val mailServer ...


1 Answers

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.

like image 162
Travis Brown Avatar answered Oct 29 '22 18:10

Travis Brown