I'm trying to understand how json4s serializes and deserializes json, specifically how it uses formats. Are there any online references that show how json4s uses the DefaultFormats
to serialize and deserialize json? The official json4s website doesn't shed much light on this.
DefaultFormats
is a provided implementation of Formats
trait.
You can see how it used in Extraction.decompose
and Extraction.extract
methods (json4s uses these methods for serialization/deserialization).
Extraction.extract
uses 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.")
}
}
}
So, json4s tries to find in Formats
custom deserializer for all unknown types.
Extraction.decompose
uses Extraction.decomposeObject
under the hood, where json4s try to serialize all types by a custom serializer:
if (formats.customSerializer(formats).isDefinedAt(a)) {
current addJValue formats.customSerializer(formats)(a)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.