Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

serialization - How do I use a @serializable scala object?

I know that you can mark a scala object as @serializable, but I don't understand what to do with the object afterwards. Do I simply treat it as a Java Serializable object?

I want to serialize the object into a stream of bytes. Can someone show me the code to transform a serialize object into either a byte array or a string?

(the googles have not been helpful with this question)

FOLLOWUP: Thanks. I now understand that I can use it like a Java Serializable object. Sometimes the obvious answer escapes me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To answer your first question: yes you can treat it as a Java Serializable object:


scala> @serializable object A
defined module A

scala> import java.io.ByteArrayOutputStream;
import java.io.ByteArrayOutputStream

scala> import java.io.ObjectOutputStream;
import java.io.ObjectOutputStream

scala> val baos = new ByteArrayOutputStream(1024)
baos: java.io.ByteArrayOutputStream = 

scala> val o = new ObjectOutputStream(baos)
o: java.io.ObjectOutputStream = java.io.ObjectOutputStream@3d689405

scala> o.writeObject(A)

scala> baos.toByteArray
res4: Array[Byte] = Array(-84, -19, 0, 5, 115, 114, 0, 24, 108, 105, 110, 101, 49, 51, 36, 111, 98, 106, 101, 99, 116, 36, 36, 105, 119, 36, 36, 105, 119, 36, 65, 36, 110, -104, -28, -53, -123, -97, -118, -36, 2, 0, 0, 120, 112)

scala> object B
defined module B

scala> o.writeObject(B)
java.io.NotSerializableException: B$
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
    at .(:13)
    at .()
    at RequestResult$.(:9)
    at RequestResult$.()
    at RequestResult$scala_repl_result()
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.tools.nsc.Interpreter$Request$...

If you want to serialize to some string format, perhaps this library may be useful, which serializes scala objects into JSON.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...