Object serialization: Difference between revisions

Added FreeBASIC
(implement in nim-lang)
(Added FreeBASIC)
 
(6 intermediate revisions by 5 users not shown)
Line 4:
=={{header|Ada}}==
This file contains the package specification containing the public definitions of the inheritance tree rooted at the type ''Message''. Each type in the inheritance tree has its own print procedure.
<langsyntaxhighlight lang="ada">with Ada.Calendar; use Ada.Calendar;
 
package Messages is
Line 28:
procedure Print(Item : Control_Message);
end Messages;</langsyntaxhighlight>
 
The next portion contains the implementation of the procedures defined in the package specification.
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
Line 98:
end Display;
end Messages;</langsyntaxhighlight>
 
The final section of code creates objects of the three message types and performs the printing, writing, and reading. The Ada attributes '' 'Class'Output'' serialize the object and write it to the specified stream. The '' 'Class'Input'' attributes call a function automatically provided by the compiler which reads from the specified stream file and returns the object read. The ''Display'' procedure takes an object in the inheritance tree rooted at ''Message'' and dispatches the correct print procedure.
 
<langsyntaxhighlight lang="ada">with Messages; use Messages;
with Ada.Streams.Stream_Io; use Ada.Streams.Stream_Io;
with Ada.Calendar; use Ada.Calendar;
Line 141:
end loop;
Close(The_File);
end Streams_Example;</langsyntaxhighlight>
Output results:
Time Stamp:2007-3-9
Line 165:
Serialization in ''ALGOL 68'' is achieved through a technique called
''straightening''.
<langsyntaxhighlight lang="algol68">MODE ENTITY = STRUCT([6]CHAR name, INT creation);
FORMAT entity repr = $"Name: "g", Created:"g$;
MODE PERSON = STRUCT(ENTITY entity, STRING email);
Line 193:
printf((person repr, i1, $l$));
printf((entity repr, i2, $l$))</langsyntaxhighlight>
'''flex'''ible length arrays (including '''string'''s), and tagged-'''union'''
types are problematic as the lengths of the arrays, and the ''tag'' of the
Line 212:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
using System.Collections.Generic;
Line 275:
}
}
}</langsyntaxhighlight>
<pre>Fido, id=1 is alive
Lupo, id=2 is alive
Line 289:
compiled with g++ -lboost_serialization serializationtest3.cpp -o serializationtest3
 
<langsyntaxhighlight lang="cpp">#include <string>
#include <fstream>
#include <boost/serialization/string.hpp>
Line 406:
w2.print( ) ;
return 0 ;
}</langsyntaxhighlight>
creating the following output:
<pre>
Line 425:
=={{header|Caché ObjectScript}}==
 
<langsyntaxhighlight lang="cos">Class Serialize.Employee Extends %SerialObject
{
 
Line 450:
Property Department As %String [ Private ];
 
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="cos">Class Serialize.Worker Extends Employee
{
 
Line 476:
Property HourlyPay As %Numeric [ Private ];
 
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="cos">Class Serialize.Example Extends %SerialObject
{
 
Line 536:
Property Workers As list Of Worker;
 
}</langsyntaxhighlight>
 
{{out|Examples}}
Line 561:
{{libheader|cl-serializer}}
 
<langsyntaxhighlight lang="lisp">(defmacro with-serialization-to-file ((stream pathname) &body body)
`(with-open-file (,stream ,pathname
:element-type '(unsigned-byte 8)
Line 572:
 
(defclass person (entity)
((name :initarg :name :initform "The Nameless One")))</langsyntaxhighlight>
 
And now the REPL log:
 
<langsyntaxhighlight lang="lisp">CL-USER> (list (make-instance 'entity)
(make-instance 'person))
 
Line 610:
Slots with :INSTANCE allocation:
NAME = "The Nameless One"
(#<ENTITY {1003C12911}> #<PERSON {1003C12A81}>)</langsyntaxhighlight>
 
=={{header|D}}==
Line 628:
Run "pbcompiler test.proto" to generate the serializable code. It should generate a D code file named test.d.
In your main file, use the following code:
<langsyntaxhighlight lang="d">import test1;
import std.stdio;
import std.file;
Line 662:
writefln("Output data:");
base.print;
}</langsyntaxhighlight>
 
=={{header|E}}==
Line 668:
(Inheritance, while supported by various features and patterns, is not a preferred design component in [[E]]; nor are simple record data structures.)
 
<langsyntaxhighlight lang="e">def makeEvent(time :int) {
return def event {
to __printOn(out) { out.print(`@@$time`) }
Line 688:
to getPosition() { return position }
}
}</langsyntaxhighlight>
 
After defining our data types, we can prepare to serialize them.
 
<langsyntaxhighlight lang="e">def surgeon := <import:org.erights.e.elib.serial.makeSurgeon>().diverge()
surgeon.addExit(makeEvent, "makeEvent")
surgeon.addExit(makeArrival, "makeArrival")</langsyntaxhighlight>
 
The 'exits' of the surgeon (so called because it cuts and joins object subgraphs) specify the points at which serialization should stop, instead replacing references to the objects with the specified names. On unserialization, the names are looked up and replaced with the corresponding objects. (The surgeon provides default exits for such things as <tt>false</tt>, <tt>true</tt>, <tt>null</tt>, and the list constructor.)
<langsyntaxhighlight lang="e">def objs := [makeEvent(timer.now()),
makeArrival(timer.now(), "Smith", 7)]
 
stdout.println(objs)
<file:objects.dat>.setBytes(surgeon.serialize(objs))
stdout.println(surgeon.unserialize(<file:objects.dat>.getBytes()))</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
Our classes will be 'struct' objects, with custom #:tostring procedures, as required. The instances are saved/restored to/from local storage. Serialization is performed by JSONifying the objects. References between instances of struct's are kept in the process. Auto-references and circular references are correctly maintained since EchoLisp version 2.11.
<langsyntaxhighlight lang="lisp">
(define (person->string self) (format "%a : person." (person-name self)))
(define (writer->string self) (format "%a: writer of %a."
Line 739:
papa → papa: father of (Simon Elvis).
elvis → Elvis : person.
</syntaxhighlight>
</lang>
{{output}}
<langsyntaxhighlight lang="lisp">
;; reboot (close the browser window)
; inspect objects.dat :
Line 770:
(define papa (local-get-value 'papa "objects.dat"))
papa → papa: father of (Antoinette papa Elvis).
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
Erlang is not object oriented. This code is based upon my understanding of the Algol 68 example above.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( object_serialization ).
 
Line 803:
print( Entity ),
io:fwrite( "\temail: ~p~n", [Email] ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 818:
=={{header|Factor}}==
The <code>serialize</code> vocabulary provides words for serializing and deserializing any Factor object other than continuations. This example demonstrates that objects may be serialized individually, one at a time. In practice, it's probably easier to serialize a collection of objects.
<langsyntaxhighlight lang="factor">USING: accessors combinators.extras io io.encodings.binary
io.files io.files.info kernel prettyprint serialize ;
IN: rosetta-code.object-serialization
Line 862:
! Print out deserialized objects.
 
[ . ] tri@</langsyntaxhighlight>
{{out}}
<pre>
Line 889:
}
</pre>
 
=={{header|FreeBASIC}}==
FreeBASIC does not support object-oriented programming such as classes and inheritance directly. However, we can simulate some aspects of object-oriented programming using procedures and user-defined types (UDTs).
 
For serialization, FreeBASIC does not have built-in support for this. We need to manually write and read each field of your UDTs to and from a file.
<syntaxhighlight lang="vbnet">Type Person
nombre As String
edad As Integer
End Type
 
Sub PrintPerson(p As Person)
Print "Name: "; p.nombre
Print "Age: "; p.edad
End Sub
 
Sub Serialize(p As Person, filename As String)
Open filename For Binary As #1
Put #1, , p.nombre
Put #1, , p.edad
Close #1
End Sub
 
Sub Deserialize(p As Person, filename As String)
Open filename For Binary As #1
Get #1, , p.nombre
Get #1, , p.edad
Close #1
End Sub
 
Dim pp As Person
pp.nombre = "Juan Hdez."
pp.edad = 52
 
Serialize(pp, "objects.dat")
Deserialize(pp, "objects.dat")
 
PrintPerson(pp)
 
Sleep</syntaxhighlight>
{{out}}
<pre>Name: Juan Hdez.
Age: 52</pre>
 
=={{header|Go}}==
Line 894 ⟶ 936:
 
A note on object oriented stuff, the object hierarchy required by the task description is implemented here with embedded structs. The polymorphism required by the task description is handled nicely with an interface. The functional polymorphism is orthogonal to the object hierarchy, not conflated with it.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,047 ⟶ 1,089:
fmt.Println(" collie, not trained, doesn't catch frisbee")
}
}</langsyntaxhighlight>
Output:
<pre>created:
Line 1,063 ⟶ 1,105:
=={{header|Groovy}}==
Sample Serializable Classes (borrowed from Java example. Sorta.):
<langsyntaxhighlight lang="groovy">class Entity implements Serializable {
static final serialVersionUID = 3504465751164822571L
String name = 'Thingamabob'
Line 1,073 ⟶ 1,115:
Person() { name = 'Clement' }
Person(name) { this.name = name }
}</langsyntaxhighlight>
 
Writing objects:
<langsyntaxhighlight lang="groovy">File objectStore = new File('objectStore.ser')
if (objectStore.exists()) { objectStore.delete() }
assert ! objectStore.exists()
Line 1,094 ⟶ 1,136:
os << new Person('Schroeder')
} catch (e) { throw new Exception(e) } finally { os?.close() }
assert objectStore.exists()</langsyntaxhighlight>
 
Reading objects:
<langsyntaxhighlight lang="groovy">def is
try {
is = objectStore.newObjectInputStream(this.class.classLoader)
Line 1,104 ⟶ 1,146:
 
objectStore.delete()
assert ! objectStore.exists()</langsyntaxhighlight>
 
Output:
Line 1,123 ⟶ 1,165:
Example uses [https://hackage.haskell.org/package/binary <tt>binary</tt>] package. Since Haskell doesn't directly support OO-style inheritance, we use a sum type instead:
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE DeriveGeneric #-}
 
module Main (main) where
Line 1,147 ⟶ 1,189:
bytes <- ByteString.readFile "objects.dat"
let employees = Binary.decode bytes
print (employees :: [Employee])</langsyntaxhighlight>
 
=={{Header|Insitux}}==
 
Insitux does not have OOP-style objects, nor a recommended way to serialise into binary. The recommended serialisation/deserialisation method ([https://www.rosettacode.org/wiki/JSON#Insitux as JSON is not fully capable]) is <code>str</code> to serialise into a string, and <code>safe-eval</code> to deserialise from string. If <code>eval</code> was used it would be vulnerable to arbitrary code execution.
 
 
<syntaxhighlight lang="insitux">
(var object {:a 1 :b "Hello, world!" [1 2 3] :c}
serialised (str object)
deserialised (safe-eval serialised))
 
(print "Object: " object)
(print "Serialised: " serialised)
(str "Deserialised: " deserialised)
</syntaxhighlight>
 
{{out}}
 
<pre>
Object: {:a 1, :b "Hello, world!", [1 2 3] :c}
Serialised: {:a 1, :b "Hello, world!", [1 2 3] :c}
Deserialised: {:a 1, :b "Hello, world!", [1 2 3] :c}
</pre>
 
=={{header|J}}==
Line 1,153 ⟶ 1,218:
This should be sufficient for this task:
 
<langsyntaxhighlight lang="j">lin_z_=:5!:5
serializeObject=:3 :0
p=. copath y
Line 1,193 ⟶ 1,258:
print__r1''
print__k1''
print__s1''</langsyntaxhighlight>
 
Here is how the last part looks in action:
 
<langsyntaxhighlight lang="j"> print__R''
room size small
print__K''
Line 1,213 ⟶ 1,278:
kitchen size medium
print__s1''
kitchen with sink size large</langsyntaxhighlight>
 
Note also that J does not attempt to distinguish, at the language level, between an object reference and something that looks like an object reference but is not. This must be done at the application level, which in turn can create a variety of opportunities and/or burdens for the program designer.
Line 1,220 ⟶ 1,285:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.io.*;
 
// classes must implement java.io.Serializable in order to be serializable
Line 1,279 ⟶ 1,344:
}
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
abstract type Hello end
 
Line 1,320 ⟶ 1,385:
sayhello(hh1)
sayhello(hh2)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.io.*
Line 1,380 ⟶ 1,445:
System.exit(1)
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,393 ⟶ 1,458:
 
=={{header|Neko}}==
<langsyntaxhighlight lang="actionscript">/* Object serialization, in Neko */
 
var file_open = $loader.loadprim("std@file_open", 2)
Line 1,433 ⟶ 1,498:
var other = unserialize(buff, $loader)
$print("deserialized:\n")
other.print()</langsyntaxhighlight>
 
{{out}}
Line 1,452 ⟶ 1,517:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import marshal, streams
type
Line 1,477 ⟶ 1,542:
print(t[0])
print(t[1])
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,487 ⟶ 1,552:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Thingy {
Line 1,538 ⟶ 1,603:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
Line 1,550 ⟶ 1,615:
There exists also a way of serializing without the GNUstep/Cocoa framework, using the runtime of Objective-C (so it could be slightly implementation dependent, see [[wp:Serialization#Objective-C|Serialization on Wikipedia]]). (I will work on it and will put here a full working example compatible with the task).
 
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
// a fantasy two level hierarchy
Line 1,705 ⟶ 1,770:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 1,711 ⟶ 1,776:
Objects which contain methods are difficult to serialize because it will want to serialize those methods too, but functions usually cannot be serialized. Instead, here we perform the task on non-object datatypes, with an outside function to print them.
 
<langsyntaxhighlight lang="ocaml">type entity = { name : string }
 
let create_entity () = { name = "Entity" }
Line 1,733 ⟶ 1,798:
 
print_entity result1;;
print_entity result2;;</langsyntaxhighlight>
 
The module which provides functions to encode arbitrary data structures as sequences of bytes is [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Marshal.html the module Marshal].
Line 1,740 ⟶ 1,805:
All objects (values and references) can be serialized using `fasl-save` (by `fasl-encode`) and deserialized using `fasl-load` (by `fasl-decode`).
 
<langsyntaxhighlight lang="scheme">
$ ol
Welcome to Otus Lisp 1.2,
Line 1,779 ⟶ 1,844:
bye-bye :/
$
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
Line 1,790 ⟶ 1,855:
=={{header|Perl}}==
{{libheader|Storable}}
<langsyntaxhighlight lang="perl">{
package Greeting;
sub new {
Line 1,824 ⟶ 1,889:
print $g2->stringify;
print $s2->stringify;
};</langsyntaxhighlight>
 
{{libheader|MooseX}}
 
The same, using [[MooseX]] to serialize to [[uses format::JSON]].
<langsyntaxhighlight lang="perl">use MooseX::Declare;
 
class Greeting {
Line 1,854 ⟶ 1,919:
print $g2->string;
print $s2->string;
</syntaxhighlight>
</lang>
This time the objects were serialized to the [http://www.json.org/ JSON] format. Other supported formats are [http://search.cpan.org/perldoc?Storable Storable] and [http://www.yaml.org/ YAML].
 
Line 1,860 ⟶ 1,925:
The serialize() and deserialize() functions handle any kind of data. Whether they are binary, text, data types, classes,
or whatever you choose to treat as such, is up to you.
<lang Phix>include builtins\serialize.e
 
<!--<syntaxhighlight lang="phix">-->
function randobj()
<span style="color: #008080;">include</span> <span style="color: #008000;">"builtins/serialize.e"</span>
-- test function (generate some random garbage)
object res
<span style="color: #008080;">function</span> <span style="color: #000000;">randobj</span><span style="color: #0000FF;">()</span>
if rand(10)<=3 then -- make sequence[1..3]
<span style="color: #000080;font-style:italic;">-- test function (generate some random garbage)</span>
res = {}
<span style="color: #004080;">object</span> <span style="color: #000000;">res</span>
for i=1 to rand(3) do
<span style="color: #008080;">if</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)<=</span><span style="color: #000000;">3</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- make sequence[1..3]</span>
res = append(res,randobj())
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
end for
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
elsif rand(10)<=3 then -- make string
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">randobj</span><span style="color: #0000FF;">())</span>
res = repeat('A'+rand(10),rand(10))
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
else
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)<=</span><span style="color: #000000;">3</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- make string</span>
res = rand(10)/2 -- half int/half float
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
end if
<span style="color: #008080;">else</span>
return res
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span> <span style="color: #000080;font-style:italic;">-- half int/half float</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">o1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">randobj</span><span style="color: #0000FF;">(),</span>
<span style="color: #000000;">o2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">randobj</span><span style="color: #0000FF;">(),</span>
<span style="color: #000000;">o3</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">randobj</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">({</span><span style="color: #000000;">o1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">o2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">o3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">fh</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"objects.dat"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"wb"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fh</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">serialize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o1</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fh</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">serialize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o2</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fh</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">serialize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o3</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fh</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"==="</span>
<span style="color: #000000;">fh</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"objects.dat"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"rb"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">deserialize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fh</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">deserialize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fh</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">deserialize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fh</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fh</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">delete_file</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"objects.dat"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
 
object o1 = randobj(),
o2 = randobj(),
o3 = randobj()
 
pp({o1,o2,o3},{pp_Nest,1})
integer fh = open("objects.dat", "wb")
puts(fh, serialize(o1))
puts(fh, serialize(o2))
puts(fh, serialize(o3))
close(fh)
 
?"==="
 
fh = open("objects.dat", "rb")
?deserialize(fh)
?deserialize(fh)
?deserialize(fh)
close(fh)
{} = delete_file("objects.dat")</lang>
{{out}}
<pre>
Line 1,910 ⟶ 1,979:
=={{header|PHP}}==
Serialization in PHP is straightforward. The built-in function [http://www.php.net/manual/en/function.serialize.php serialize()] handles it in a single statement.
<langsyntaxhighlight lang="php">$myObj = new Object();
$serializedObj = serialize($myObj);</langsyntaxhighlight>
In order to un-serialize the object, use the [http://www.php.net/manual/en/function.unserialize.php unserialize()] function. Note that the class of object must be defined in the script where un-serialization takes place, or the class' methods will be lost.
 
Line 1,919 ⟶ 1,988:
back. This functionality is also used internally for database access and
interprocess-communication.
<langsyntaxhighlight PicoLisplang="picolisp">(class +Point)
# x y
 
Line 1,948 ⟶ 2,017:
(out "objects.dat"
(pr (val P) (getl P))
(pr (val C) (getl C)) )</langsyntaxhighlight>
<langsyntaxhighlight PicoLisplang="picolisp">(in "objects.dat"
(putl (setq A (box (rd))) (rd))
(putl (setq B (box (rd))) (rd)) )
 
(print> A)
(print> B)</langsyntaxhighlight>
Output:
<pre>Point 3,4
Line 1,962 ⟶ 2,031:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python"># Object Serialization in Python
# serialization in python is accomplished via the Pickle module.
# Alternatively, one can use the cPickle module if speed is the key,
Line 1,998 ⟶ 2,067:
 
i1.printName()
i2.printName()</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,005 ⟶ 2,074:
 
The serialization needs to be included with
<syntaxhighlight lang ="racket">(require racket/serialize)</langsyntaxhighlight>
The rest is covered by the Racket language.
 
(I have elided the paths in objects.dat -- you wouldn't be able to use them anyway)
 
<langsyntaxhighlight lang="racket">#lang racket
;; Object Serialization: Tim Brown, Oct. 2014
(require racket/serialize)
Line 2,081 ⟶ 2,150:
(printf "With siblings:\t~s (he hasn't any)~%" (send cloned-john ->string #:show '(siblings)))
(printf "With children:\t~s~%" (send cloned-john ->string #:show '(children)))
(printf "With both:\t~s~%" (send cloned-john ->string #:show '(siblings children)))</langsyntaxhighlight>
 
{{out}}
Line 2,109 ⟶ 2,178:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line># Reference:
# https://docs.raku.org/language/classtut
# https://github.com/teodozjan/perl-store
Line 2,142 ⟶ 2,211:
my $r2 = from_file('objects.dat');
say "Rectangle2 is of type ", $r2.WHAT;
say "Rectangle2 area is ", $r2.area();</langsyntaxhighlight>
{{out}}
<pre>Create Rectangle1 with area 100
Line 2,157 ⟶ 2,226:
=={{header|Ruby}}==
The core class <code>[http://www.ruby-doc.org/core/classes/Marshal.html Marshal]</code> handles object serialization. The <code>dump</code> method serializes an object, and the <code>load</code> method reconstitutes it.
<langsyntaxhighlight lang="ruby">class Being
def initialize(specialty=nil)
@specialty=specialty
Line 2,226 ⟶ 2,295:
end.join("\n\n")
)
puts "END LOADED DIVERSE COLLECTION"</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 2,232 ⟶ 2,301:
=== Enum ===
Dependencies:
<langsyntaxhighlight TOMLlang="toml">serde = { version = "1.0.89", features = ["derive"] }
bincode = "1.1.2"</langsyntaxhighlight>
 
<langsyntaxhighlight Rustlang="rust">use std::fmt;
 
use bincode::{deserialize, serialize};
Line 2,282 ⟶ 2,351:
 
Ok(())
}</langsyntaxhighlight>
{{out}}
<pre>Rover is a dog with brown fur
Line 2,299 ⟶ 2,368:
=== Trait ===
Dependencies:
<langsyntaxhighlight TOMLlang="toml">serde = { version = "1.0.89", features = ["derive"] }
bincode = "1.1.2"
typetag = "0.1.1"</langsyntaxhighlight>
 
<langsyntaxhighlight Rustlang="rust">use std::fmt::{self, Debug, Display};
 
use bincode::{deserialize, serialize};
Line 2,388 ⟶ 2,457:
 
Ok(())
}</langsyntaxhighlight>
{{out}}
<pre>Rover is a dog with brown fur
Line 2,407 ⟶ 2,476:
{{works with|Tcl|8.6}}
''This example uses an experimental package, available from [http://wiki.tcl.tk/23444 The Tcler's Wiki].
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
package require TclOO::serializer 0.1
 
Line 2,458 ⟶ 2,527:
set obj [oo::deserialize [read $f]]
close $f
$obj printGreetings</langsyntaxhighlight>
 
=={{header|TXR}}==
 
TXR Lisp has good support for object serialization. The object file format for compiled files (<code>.tlo</code> files) depends on it.
 
<syntaxhighlight lang="txrlisp">(defstruct shape ()
(pos-x 0.0) (pos-y 0.0))
 
(defstruct circle (shape)
radius)
 
(defstruct ellipse (shape)
min-radius maj-radius)
 
(defvarl shapes (list (new circle radius 3.0)
(new ellipse min-radius 4.0 maj-radius 5.0)))
 
(put-line "original shapes:")
(prinl shapes)
 
(file-put "shapes.tl" shapes)
 
(put-line "dump of shapes.tl file:")
(put-line (file-get-string "shapes.tl"))
 
(put-line "object list read from file:")
(prinl (file-get "shapes.tl"))</syntaxhighlight>
 
{{out}}
 
<pre>original shapes:
(#S(circle pos-x 0.0 pos-y 0.0 radius 3.0) #S(ellipse pos-x 0.0 pos-y 0.0 min-radius 4.0 maj-radius 5.0))
dump of shapes.tl file:
(#S(circle pos-x 0.0 pos-y 0.0 radius 3.0) #S(ellipse pos-x 0.0 pos-y 0.0 min-radius 4.0 maj-radius 5.0))
 
object list read from file:
(#S(circle pos-x 0.0 pos-y 0.0 radius 3.0) #S(ellipse pos-x 0.0 pos-y 0.0 min-radius 4.0 maj-radius 5.0))</pre>
 
An object can be given a <code>print</code> method which has a Boolean argument whether to print "pretty" (meaning in some nicely formatted form for humans, not necessarily a serial notation readable by machine). A print method can return the <code>:</code> (colon) symbol to indicate that it declines to print; the default implementation should be used. With that it it possible to do
 
<syntaxhighlight lang="txrlisp">(defstruct shape ()
(pos-x 0.0) (pos-y 0.0))
 
(defstruct circle (shape)
radius
(:method print (me stream pretty-p)
(if pretty-p
(put-string `#<circle of radius @{me.radius} at coordinates (@{me.pos-x}, @{me.pos-y})>`)
:)))
 
(let ((circ (new circle radius 5.3)))
(prinl circ) ;; print machine readably
(pprinl circ)) ;; print pretty</syntaxhighlight>
 
{{out}}
 
<pre>#S(circle pos-x 0.0 pos-y 0.0 radius 5.3)
#<circle of radius 5.3 at coordinates (0, 0)></pre>
 
=={{header|Wren}}==
{{libheader|Wren-json}}
Currently, Wren's only facility for serializing objects is to use the above JSON module. Also this module can only 'stringify' objects of built-in types so we need to provide a suitable string representation for each user-defined class.
<langsyntaxhighlight ecmascriptlang="wren">import "./json" for JSON
import "io" for File, FileFlags
 
Line 2,523 ⟶ 2,650:
 
System.print("\nContents of objects.dat are:")
System.print(File.read(fileName))</langsyntaxhighlight>
 
{{out}}
Line 2,539 ⟶ 2,666:
zkl can serialize a "root class" (usually a file but any static (ie parentless) class) to bit bucket (such as File). This is done via reflection. The state of the class(es) are not stored so no image write/read. In the "normal" course of events, this isn't used, programs are compiled on the fly and run. However, there is extensive support to pre-compile and package files into applications or just pre-compile for faster load times (or to create an image that can be compiled into C code (which is done to package the compiler with the VM). When the compiler writes a class or app to a file, the preferred extension is ".zsc", which is what the Import method looks for. But no matter, we have ways ...
 
<langsyntaxhighlight lang="zkl">class [static] ARootClass{ // A top level class, no instances
class A{ self.println(" constructor"); } // a regular class
class B(A){ // ditto
Line 2,564 ⟶ 2,691:
rc.B().println(); // create a new instance of B
// prints:
x is 123</langsyntaxhighlight>
 
 
2,122

edits