Created
May 31, 2014 07:04
-
-
Save MishaelRosenthal/6131457169513a596ec3 to your computer and use it in GitHub Desktop.
Json Spray usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.liveperson.predictivedialer.examples.misc | |
| import spray.json._ | |
| import spray.json.DefaultJsonProtocol._ | |
| import java.io.{PrintWriter, FileWriter} | |
| import scala.concurrent.duration._ | |
| /** | |
| * Created with IntelliJ IDEA. | |
| * User: mishaelr | |
| * Date: 1/26/14 | |
| * Time: 5:02 PM | |
| */ | |
| object converters { | |
| implicit object FiniteDurationJsonFormat extends RootJsonFormat[FiniteDuration]{ | |
| def write(dur: FiniteDuration) = JsObject( | |
| "length" -> JsNumber(dur.length), | |
| "unit" -> JsString(dur.unit.toString) | |
| ) | |
| def read(value: JsValue) = { | |
| value.asJsObject.getFields("length", "unit") match { | |
| case Seq(JsNumber(len), JsString(unit)) => FiniteDuration(len.toLong, unit.toLowerCase) | |
| case _ => deserializationError("FiniteDuration expected") | |
| } | |
| } | |
| } | |
| } | |
| object MapSerialization extends App{ | |
| import converters.FiniteDurationJsonFormat | |
| sealed trait MyEvent{ | |
| def session: String | |
| } | |
| case class EventA(session: String) extends MyEvent | |
| case class EventB(session: String) extends MyEvent | |
| println(EventA("session1").getClass.getSimpleName) | |
| val maps: Map[String, List[MyEvent]] = Map( | |
| "session1" -> List(EventA("session1"), EventB("session1"), EventA("session1")), | |
| "session2" -> List(EventB("session1"), EventA("session1"))) | |
| val asStrLists: Map[String, List[(String, FiniteDuration)]] = maps.mapValues{list => list.map(event => event.getClass.getSimpleName -> 1.second)} | |
| println("asStrLists " + asStrLists) | |
| val asJsons = for { | |
| asStr <- asStrLists | |
| } yield asStr.toJson | |
| def using[A <: {def close(): Unit}, B](resource: A)(f: A => B): B = | |
| try f(resource) finally resource.close() | |
| def writeIteratorToFile(path: String, data: Iterable[String]): Unit = { | |
| using(new PrintWriter(new FileWriter(path)))(writer => data.foreach(writer.println)) | |
| } | |
| writeIteratorToFile("temp.json", asJsons.map(_.toString())) | |
| val source = scala.io.Source.fromFile("temp.json") | |
| val asStrListsAfter = source.getLines().map(_.asJson.convertTo[(String, List[(String, FiniteDuration)])]).toMap | |
| println("asStrListsAfter " + asStrListsAfter) | |
| require(asStrListsAfter == asStrLists) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment