【发布时间】:2018-11-18 22:17:47
【问题描述】:
我试图了解json4s 如何序列化和反序列化 json,特别是它如何使用格式。是否有任何在线参考资料显示 json4s 如何使用DefaultFormats 序列化和反序列化 json?官方的 json4s 网站并没有对此进行过多说明。
【问题讨论】:
标签: scala serialization deserialization
我试图了解json4s 如何序列化和反序列化 json,特别是它如何使用格式。是否有任何在线参考资料显示 json4s 如何使用DefaultFormats 序列化和反序列化 json?官方的 json4s 网站并没有对此进行过多说明。
【问题讨论】:
标签: scala serialization deserialization
DefaultFormats 是Formats trait 的提供实现。
您可以在Extraction.decompose 和Extraction.extract 方法中看到它是如何使用的(json4s 使用这些方法进行序列化/反序列化)。
Extraction.extract 使用Extraction.convert:
private[this] def convert(key: String, target: ScalaType, formats: Formats): Any = {
val targetType = target.erasure
targetType match {
case tt if tt == classOf[String] => key
case tt if tt == classOf[Symbol] => Symbol(key)
case tt if tt == classOf[Int] => key.toInt
case tt if tt == classOf[JavaInteger] => JavaInteger.valueOf(key.toInt)
case tt if tt == classOf[BigInt] => key.toInt
case tt if tt == classOf[Long] => key.toLong
case tt if tt == classOf[JavaLong] => JavaLong.valueOf(key.toLong)
case tt if tt == classOf[Short] => key.toShort
case tt if tt == classOf[JavaShort] => JavaShort.valueOf(key.toShort)
case tt if tt == classOf[Date] => formatDate(key, formats)
case tt if tt == classOf[Timestamp] => formatTimestamp(key, formats)
case _ =>
val deserializer = formats.customKeyDeserializer(formats)
val typeInfo = TypeInfo(targetType, None)
if(deserializer.isDefinedAt((typeInfo, key))) {
deserializer((typeInfo, key))
} else {
fail("Do not know how to deserialize key of type " + targetType + ". Consider implementing a CustomKeyDeserializer.")
}
}
}
所以,json4s 尝试在Formats 中找到所有未知类型的自定义反序列化器。
Extraction.decompose 在后台使用Extraction.decomposeObject,其中 json4s 尝试通过自定义序列化程序序列化所有类型:
if (formats.customSerializer(formats).isDefinedAt(a)) {
current addJValue formats.customSerializer(formats)(a)
}
【讨论】: