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



我正在尝试使用Json4s将case类转换为Json字符串。我得到了异常

MappingException: Can't find ScalaSig for class java.lang.Object

如果我只用另一个trait扩展我的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 reflect库依赖,如下所示:

"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

您应该为自定义序列化添加类。它可以是

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 .

相关内容

  • 没有找到相关文章

最新更新