如何用喷雾对自定义物体进行jsonize?

时间:2013-10-23 08:43:38

标签: json scala spray

我正在尝试执行以下操作(我使用spray-json_2.9.2 v1.2.3,因为我使用scala 2.9.2)

import spray.json._
import spray.json.DefaultJsonProtocol
import DefaultJsonProtocol._

case class TestMe(key: String, value: String)
object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val prot = jsonFormat4(TestMe)
}

但是我收到了编译错误:

  

TestMe.type(带有基础类型对象   com ... TestMe)[INFO]要求:(?,?,?,?)=>   ? [INFO]注意:隐含值prot不适用于此处,因为它   在应用程序点之后,它缺少显式结果类型   [INFO]隐式val prot = jsonFormat4(TestMe)

我做错了什么我只是跟着文档:https://github.com/spray/spray-json#providing-jsonformats-for-case-classes

感谢

1 个答案:

答案 0 :(得分:9)

如果您查看所有jsonFormat个签名,那么它需要一个函数,更准确地说是apply

case class TestMe(key: String, value: String)
object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val prot = jsonFormat2(TestMe.apply)
}

AND jsonFormat不是一个宏函数,它只是重载,所以最后的数字应该等于case类

中args的数量

在此示例中,您的案例类有两个参数,因此您需要jsonFormat2而不是jsonFormat4

并且最好将伴随对象MyJsonProtocol重命名为TestMe,这将减少带有隐含的显式导入