scala - json4s如何使用DefaultFormats对json进行序列化和反序列化?
问题描述
我试图了解json4s如何序列化和反序列化 json,特别是它如何使用格式。是否有任何在线参考资料显示 json4s 如何使用DefaultFormats
来序列化和反序列化 json?官方的 json4s 网站并没有对此提供太多说明。
解决方案
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)
}
推荐阅读
- android - 使用 Dagger 2 注入 Androidx 片段
- spring-boot - spring cloud - 关闭代理微服务后没有可用的bean importRegistry
- c# - WebApi 项目和 MVC 项目在同一个解决方案中是最佳实践吗?
- python - python重新匹配只出现一次(不重复连续)
- sql - 使用 RANK() OVER 计数时跳过空值
- python - 无法在 TensorFlow Estimator 中训练 Keras 预训练模型
- node.js - Mongoose:有条件地在嵌套文档数组中进行原子查找和更新
- python - 我在 iPad 上使用 Python 编译器来练习程序,但是看不到任何图形视觉效果
- javascript - 保存来自 Whatsapp Web 的未知人员的姓名和数量
- java - 查找要在 pom .XML 文件中使用的正确 Junit 版本