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
Have a look at Lift-Json. It is part of the Lift web framework, but can be used as a stand-alone library. It can parse json into case classes (and collections of those, e.g., lists and maps), and it does not require you to add annotations. It also supports rendering classes as json, and merging and querying of json.
Here is an example taken from their website:
I personally prefer
lift-json
, but it's pretty easy to do this with Play's JSON library:Right now this produces the following:
So yeah, looks about right.
Try Jerkson lib: https://github.com/codahale/jerkson/
It is a json library for scala based on Jackson. It is included to play 2: http://www.playframework.org/documentation/2.0.2/ScalaJson
Example:
I suggest to use Jackson JSON processor. It works both for Java and Scala. You just add annotations to your classes which describe how you want to map JSON data to your native objects.
An example:
This solution has a slight hassle that you have to annotate every field with
@BeanProperty
, but I don't know a simpler way.Remark: As far as I know, Jackson doesn't use
javax.bean.Introspector
, it tries to find getters/setters by examining the methods by itself. If it did, things would have been easier, it would be possible to write justconvert to jsvalue by using Json.parse(string) then add operator as[T] to extract the value