首页 > 解决方案 > json4s如何使用DefaultFormats对json进行序列化和反序列化?

问题描述

我试图了解json4s如何序列化和反序列化 json,特别是它如何使用格式。是否有任何在线参考资料显示 json4s 如何使用DefaultFormats来序列化和反序列化 json?官方的 json4s 网站并没有对此提供太多说明。

标签: scalaserializationdeserialization

解决方案


DefaultFormats是提供的Formatstrait 实现。

你可以看到它是如何在Extraction.decomposeExtraction.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)
}

推荐阅读