繁体   English   中英

json4s如何使用DefaultFormats序列化和反序列化json?

[英]How does json4s use DefaultFormats to serialize and deserialize json?

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

DefaultFormatsFormats特性的提供的实现。

您可以看到它在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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM