Search code examples
scalajson4s

Can't get json4s to render my case class?


I set up a SBT console like...

import org.json4s._
import org.json4s.native.JsonMethods._
import org.json4s.JsonDSL._
case class TagOptionOrNull(tag: String, optionUuid: Option[java.util.UUID], uuid: java.util.UUID)
val t1 = new TagOptionOrNull("t1", Some(java.util.UUID.randomUUID), java.util.UUID.randomUUID)
val t2 = new TagOptionOrNull("t2", None, null)

I'm trying to see json4s's behavior around null vs Option[UUID]. But I can't figure out the invocation to get it to make my case class a String of JSON.

scala> implicit val formats = DefaultFormats
formats: org.json4s.DefaultFormats.type = org.json4s.DefaultFormats$@614275d5

scala> compact(render(t1))
<console>:23: error: type mismatch;
 found   : TagOptionOrNull
 required: org.json4s.JValue
    (which expands to)  org.json4s.JsonAST.JValue
       compact(render(t1))

What am I missing?


Solution

  • Serialization.write should be able to serialise case class like so

    import org.json4s.native.Serialization.write
    implicit val formats = DefaultFormats ++ JavaTypesSerializers.all
    println(write(t1))
    

    which should output

    {"tag":"t1","optionUuid":"95645021-f60c-4708-8bf3-9d5609559fdb","uuid":"19cc4979-5836-4edf-aedd-dcb3e96f17d6"}
    

    Note to serialise UUID we need JavaTypeSerializers formats from

    libraryDependencies += "org.json4s" %% "json4s-ext" % version