Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trait Container {
- def aa: String
- def bb: Int
- }
- case class First(aa: String, bb: Int) extends Container
- case class Second(aa: String, bb: Int) extends Container
- implicit val aaContainerFormat: Format[First] = Json.format[First]
- implicit val bbContainerFormat: Format[Second] = Json.format[Second]
- implicit def nodeContainerReads: Reads[Container] =
- try {
- Json.format[First].map(x => x: Container) or
- Json.format[Second].map(x => x: Container)
- } catch {
- case e: Exception => Reads {
- case _ => JsError(JsonValidationError("Cannot De-serialize value."))
- }
- }
- implicit def nodeContainerWrites = new Writes[Container] {
- override def writes(node: Container): JsValue = node match {
- case a: First => Json.toJson(a)
- case b: Second => Json.toJson(b)
- case _ => Json.obj("error" -> "wrong Json")
- }
- }
- // Example Usage....
- val spark: SparkSession = SparkSession.builder.appName("Unit Test").getOrCreate()
- val js: Container = First("unit", "test")
- spark.createDataFrame(Seq(js))
Add Comment
Please, Sign In to add comment