无法获取json4s来呈现我的案例类?

时间:2019-05-23 19:05:27

标签: scala json4s

我设置了一个SBT控制台,例如...

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)

我正在尝试查看json4s在null vs Option [UUID]周围的行为。但是我无法弄清楚该调用是否可以使我的case类成为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))

我想念什么?

1 个答案:

答案 0 :(得分:1)

Serialization.write应该能够像这样序列化案例类

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

应输出

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

注意要序列化UUID,我们需要

JavaTypeSerializers格式
libraryDependencies += "org.json4s" %% "json4s-ext" % version