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

时间:2018-11-18 22:17:48

标签: scala serialization deserialization

我试图了解json4s如何对json进行序列化和反序列化,特别是它如何使用格式。是否有任何在线参考资料显示json4s如何使用import google.oauth2.credentials credentials = google.oauth2.credentials.Credentials( 'access_token') 来序列化和反序列化json?官方的json4s网站对此没有太多说明。

1 个答案:

答案 0 :(得分:0)

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,其中json4尝试通过自定义序列化程序序列化所有类型:

if (formats.customSerializer(formats).isDefinedAt(a)) {
  current addJValue formats.customSerializer(formats)(a)
}