Guest User

Untitled

a guest
Jan 23rd, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. trait Container {
  2. def aa: String
  3. def bb: Int
  4. }
  5.  
  6. case class First(aa: String, bb: Int) extends Container
  7. case class Second(aa: String, bb: Int) extends Container
  8.  
  9. implicit val aaContainerFormat: Format[First] = Json.format[First]
  10.  
  11. implicit val bbContainerFormat: Format[Second] = Json.format[Second]
  12.  
  13. implicit def nodeContainerReads: Reads[Container] =
  14. try {
  15. Json.format[First].map(x => x: Container) or
  16. Json.format[Second].map(x => x: Container)
  17. } catch {
  18. case e: Exception => Reads {
  19. case _ => JsError(JsonValidationError("Cannot De-serialize value."))
  20. }
  21. }
  22.  
  23. implicit def nodeContainerWrites = new Writes[Container] {
  24. override def writes(node: Container): JsValue = node match {
  25. case a: First => Json.toJson(a)
  26. case b: Second => Json.toJson(b)
  27. case _ => Json.obj("error" -> "wrong Json")
  28. }
  29. }
  30.  
  31. // Example Usage....
  32. val spark: SparkSession = SparkSession.builder.appName("Unit Test").getOrCreate()
  33. val js: Container = First("unit", "test")
  34.  
  35. spark.createDataFrame(Seq(js))
Add Comment
Please, Sign In to add comment