JSON Operation by Scala

Recently, I’m doing a subscription system for my current company. The content of subscription is to crawl data from another system. The most important thing is that the data is async and from multiple channels. My solution is to use Akka scheduler to deal with async issue. For multiple channels, I use MySQL to store temp data together and finally fetch them again and email them.

So when I decide which data structure to use, I choose Map, but considering I need to use string/text to store data to DB. things became not good, because converting string to Map is not a good method. Now JSON helps me a lot.

1. import some libs

import play.api.libs.json._

2. build a JSON by Scala

var bufJson = new JsArray()
// here you need to return back, since append will not return back
bufJson = bufJson.append(Json.obj{"status" -> "add"})

3. transfer JSON to String

val dataString = bufJson.toString()

4. transfer string back to JSON

5. How to fetch data in JSON

// "time" is your key, dataJson is JsValue/JsObject which gets from Json.obj or Json.parse
val time = dataJson.\("time")
// you can convert the result to any type
val time = dataJson.\("time").as[String]
// if there is sub-JSON in result you can convert to JsObject to benefit next step
val time1 = dataJson.\("time").as[JsObject]