[英]Getting Exception while converting case class to Json using Json4s
我正在尝试使用Json4s
将案例类转换为Json String。 我正在例外
MappingException:找不到类java.lang.Object的ScalaSig
如果我仅扩展具有其他特征的案例类,就会发生这种情况。
我的代码如下:
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]
也存在相同的问题。
当我检查stacktrace并进行后续搜索时,我发现问题出在反射,这是由于Scala版本不匹配所致。 因此,我添加了scala反映库依赖关系,如下所示:
"org.scala-lang" % "scala-reflect" % "2.11.7",
"org.scala-lang" % "scalap" % "2.11.7"
但即使在那之后,我仍然遇到相同的错误。 我已经通过使用BigInt
和BigDecimal
而不是Long和Double来解决此问题。
有人可以帮助我理解此问题以及如何使用Long和Double本身解决该问题。
Json4s Version : 3.2.11
Scala Version : 2.11.7
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 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.