使用Json4s将case类转换为Json时获取Exception

时间:2015-09-29 07:53:01

标签: json scala reflection json4s

我正在尝试使用Json4s将案例类转换为Json String。我得到了例外

  

MappingException:找不到类java.lang.Object的ScalaSig

如果我只使用另一个特征扩展我的case类,就会发生这种情况。

我的代码如下:

trait Integration {
  val thirdpartyId: Option[Long]
}

trait HrIntegration extends Integration {
  override val thirdpartyId: Option[Long] = getValue
  def getValue = {
    Some(100L)
  }
}

case class Employee(id: Long, name: String, age: Long) extends HrIntegration


object Test extends App {
  import org.json4s.Extraction
  import org.json4s.jackson.JsonMethods._
  import org.json4s.DefaultFormats
  implicit lazy val serializerFormats = DefaultFormats
  val emp = Employee(1, "Yadu", 27)
  val jValue = Extraction.decompose(emp)
  val jsonString = compact(jValue)
  println(jsonString)
}

如果我将Option[Long]转换为Option[BigInt],则可以正常使用。同样的问题也是Option[Double]

当我浏览堆栈跟踪和随后的谷歌搜索时,由于scala版本不匹配,我发现问题在于反射。 所以我添加了scala反映库依赖,如下所示:

"org.scala-lang" % "scala-reflect" % "2.11.7",
"org.scala-lang" % "scalap" % "2.11.7"

但即使在那之后,我也遇到了同样的错误。我目前已使用BigIntBigDecimal代替Long和Double修复了此问题。

有人可以帮我理解这个问题以及如何通过使用Long和Double来解决它。

Json4s Version : 3.2.11
Scala Version : 2.11.7

1 个答案:

答案 0 :(得分:2)

Yadu,您应该添加自定义序列化的类。它可能看起来像

class EmployeeSerializer extends CustomSerializer[Employee](format => (
  {
    case JObject(JField("id", JInt(i)) :: JField("name", JString(n)) :: JField("age", JInt(a)) ::Nil) =>
      new Employee(i.longValue, n, a.longValue)
  },
  {
    case x @ Employee(i: Long, n: String, a: Long) =>
      JObject(JField("id", JInt(BigInt(i))) ::
        JField("name",   JString(n)) ::
        JField("age",   JInt(BigInt(a))) :: Nil)
  }
  ))

您还应该修改格式

implicit val formats = DefaultFormats + new EmployeeSerializer

所以,结果是:

import org.json4s._

trait Integration {
  val thirdpartyId: Option[Long]
}
trait HrIntegration extends Integration {
  override val thirdpartyId: Option[Long] = getValue
  def getValue = {
    Some(100L)
  }
}
case class Employee(id: Long, name: String, age: Long) extends HrIntegration

class EmployeeSerializer extends CustomSerializer[Employee](format => (
  {
    case JObject(JField("id", JInt(i)) :: JField("name", JString(n)) :: JField("age", JInt(a)) ::Nil) =>
      new Employee(i.longValue, n, a.longValue)
  },
  {
    case x @ Employee(i: Long, n: String, a: Long) =>
      JObject(JField("id", JInt(BigInt(i))) ::
        JField("name",   JString(n)) ::
        JField("age",   JInt(BigInt(a))) :: Nil)
  }
  ))

object Test extends App {
  import org.json4s.Extraction
  import org.json4s.DefaultFormats
  implicit val formats = DefaultFormats + new EmployeeSerializer
  val emp = Employee(1, "Yadu", 27)
  val jValue = Extraction.decompose(emp)
  println(jValue)
}

它返回:

JObject(List((id,JInt(1)), (name,JString(Yadu)), (age,JInt(27))))

您可以在json4s项目的页面上找到更多信息:https://github.com/json4s/json4s#serializing-non-supported-types