加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala Pickling用于Json序列化和反序列化?

发布时间:2020-12-16 09:06:52 所属栏目:安全 来源:网络整理
导读:对于我的项目,dijon,我想知道是否可以将 Scala pickling用于JSON serialization和 deserialization. 具体来说,我想要这样的东西def toJsonString(json:JSON,prettyPrint:Boolean = false):String和def fromJsonString(json:String):JSON.如何使用酸洗来
对于我的项目,dijon,我想知道是否可以将 Scala pickling用于JSON serialization和 deserialization.
具体来说,我想要这样的东西def toJsonString(json:JSON,prettyPrint:Boolean = false):String和def fromJsonString(json:String):JSON.如何使用酸洗来创建这两种辅助方法?

解决方法

这取决于最方便您使用的方法.这些是您所拥有的选择的粗略草图:

import scala.pickling._,json._    

 // Uses macros implicitly on Scope
 def toJSONString[A](obj: A,prettyPrint: Boolean = false)(implicit pickler: A => JSONPickle) = {
    val json = pickler(obj)
    myPrettyPrinter.print(json.value,prettyPrint)
 }

 // Uses macros defined elsewhere
 def toJSONString(obj: Any,prettyPrint: Boolean = false) = {
    val json = classToPicklerMap(obj.getClass)(obj)
    myPrettyPrinter.print(json.value,prettyPrint)
 }

 // Uses runtime reflection
 def toJSONString(obj: Any,prettyPrint: Boolean = false) = {
    val json = obj.pickle
    myPrettyPrinter.print(json.value,prettyPrint)
 }

 // Uses macros implicitly on scope
 def fromJSONString[A](json: String)(implicit unpickler: JSONPickle => A): A = {
    unpickler(JSONPickle(json))
 }

 // Uses macros defined elsewhere #1
 def fromJSONString[A](json: String)(implicit c: ClassTag[A]) = {
    classnameToUnpicklerMap(c.runtimeClass.getName)(json).asInstanceOf[A]
 }

 // Uses macros defined elsewhere #2
 def fromJSONString(json: String): Any = {
    val className = parseClassName(json) // Class name is stored in "tpe" field in the JSON    
    classnameToUnpicklerMap(className)(json)
 }

 // Uses runtime reflection
 def fromJSONString(json: String) = JSONPickler(json).unpickle

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读