Skip to content

Instantly share code, notes, and snippets.

@lombardo-chcg
Created March 14, 2019 16:06
Show Gist options
  • Select an option

  • Save lombardo-chcg/42dcc7da702b0aa3fb5ab5e0259f76ec to your computer and use it in GitHub Desktop.

Select an option

Save lombardo-chcg/42dcc7da702b0aa3fb5ab5e0259f76ec to your computer and use it in GitHub Desktop.
/*
Ammonite script
http://ammonite.io
*/
import $ivy.{
`org.json4s:json4s-ext_2.12:3.5.0`,
`org.json4s:json4s-jackson_2.12:3.5.0`,
`org.json4s:json4s-native_2.12:3.5.0`,
`org.scalaj:scalaj-http_2.12:2.3.0`,
`com.sksamuel.avro4s:avro4s-core_2.12:2.0.4`,
`com.sksamuel.avro4s:avro4s-json_2.12:2.0.4`
}
import org.json4s._
import org.json4s.native.JsonMethods._
import org.json4s.JsonDSL._
import org.apache.avro.generic.GenericRecord
import org.apache.avro.Schema
import com.sksamuel.avro4s.{Decoder, Encoder, RecordFormat, SchemaFor}
import com.sksamuel.avro4s.json.JsonToAvroConverter
// case classes to convert to avro records
case class Example1(a: String, b: Int, c: Option[Long])
case class Example2(a: String, b: Int, c: Option[Long], d: JValue)
// converter machinery
trait AvroConverter[T] {
def toAvro: GenericRecord
}
object AvroConverterInstances {
implicit class ProductConverter[T <: Product with Serializable : Encoder : Decoder : SchemaFor](entity: T) extends AvroConverter[T] {
def toAvro: GenericRecord = RecordFormat[T].to(entity)
}
// help needed here...
// implicit class JValueSchemaFor(value: JValue) extends SchemaFor[JValue] {
// def schema: Schema = new JsonToAvroConverter("com.example").convert("fields", value)
// }
//
// implicit object JValueEncoder extends Encoder[JValue] {
// override def encode(value: JValue, schema: Schema): AnyRef = ???
// }
//
// implicit object JValueDecoder extends Decoder[JValue] {
// override def decode[T](value: T, schema: Schema): AnyRef = ???
// }
}
// our example
object App {
import AvroConverterInstances._
def main(): Unit = {
// this compiles and works perfectly
val ex1 = Example1("z", 100, Some(0L))
val record1 = ex1.toAvro
println(record1)
val ex2 = Example2("z", 100, Some(0L), JNull)
// the following line does not compile: 'value toAvro is not a member of ammonite.$file.Avro4s-Product-Jvalue-example.Example2'
// val record2 = ex2.toAvro
// println(record2)
}
}
App.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment