2

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?

Bob Kuhar
  • 10,838
  • 11
  • 62
  • 115

1 Answers1

2

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
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
  • works great, mario. But now I don't know the difference between `render` and `write` (beyond `render` doesn't work for my simpleton use case). `render` only works with that DSL stuff? – Bob Kuhar May 24 '19 at 21:34
  • 1
    `render` takes `JValue` not a case class. Confusingly, render appears to take primitive values, for example, `render(List(1,2))`, however this argument is implicitly converted to `JValue` using `seq2jvalue`. For case classes, I think we need `write`. – Mario Galic May 24 '19 at 21:53