Scala 酸洗:如何? [英] Scala pickling: how?

查看:50
本文介绍了Scala 酸洗:如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用pickling"序列化是 Scala,并且我看到了相同的示例来演示它:

I'm trying to use "pickling" serialization is Scala, and I see the same example demonstrating it:

import scala.pickling._
import json._

val pckl = List(1, 2, 3, 4).pickle

去酸洗和酸洗一样简单:

Unpickling is just as easy as pickling:

val lst = pckl.unpickle[List[Int]]

这个例子提出了一些问题.首先,它跳过对象到字符串的转换.显然你需要调用 pckl.value 来获取 json 字符串表示.

This example raises some question. First of all, it skips converting of object to string. Apparently you need to call pckl.value to get json string representation.

Unpickling 更令人困惑.反序列化是将字符串(或字节)转换为对象的行为.如果没有对象的字符串/二进制表示,这个示例"如何演示反序列化?

Unpickling is even more confusing. Deserialization is an act of turning string (or bytes) into an object. How come this "example" demonstrates deserialization if there is no string/binry representation of object?

那么,如何使用酸洗库反序列化简单对象?

So, how do I deserialize simple object with pickling library?

推荐答案

使用类型系统和案例类来实现您的目标.你可以在你的层次结构中解压到一些高级类型(直到并包括 AnyRef).下面是一个例子:

Use the type system and case classes to achieve your goals. You can unpickle to some superior type in your hierarchy (up to and including AnyRef). Here is an example:

trait Zero
case class One(a:Int) extends Zero
case class Two(s:String) extends Zero

object Test extends App {
  import scala.pickling._
  import json._

  // String that can be sent down a wire
  val wire: String = Two("abc").pickle.value

  // On the other side, just use a case class
  wire.unpickle[Zero] match {
    case One(a) => println(a)
    case Two(s) => println(s)
    case unknown => println(unknown.getClass.getCanonicalName)
  }
}

这篇关于Scala 酸洗:如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆