Object serialization: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: quote filename)
m (syntax highlighting fixup automation)
Line 4: Line 4:
=={{header|Ada}}==
=={{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.
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.
<lang ada>with Ada.Calendar; use Ada.Calendar;
<syntaxhighlight lang="ada">with Ada.Calendar; use Ada.Calendar;


package Messages is
package Messages is
Line 28: Line 28:
procedure Print(Item : Control_Message);
procedure Print(Item : Control_Message);
end Messages;</lang>
end Messages;</syntaxhighlight>


The next portion contains the implementation of the procedures defined in the package specification.
The next portion contains the implementation of the procedures defined in the package specification.
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
Line 98: Line 98:
end Display;
end Display;
end Messages;</lang>
end Messages;</syntaxhighlight>


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.
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.


<lang ada>with Messages; use Messages;
<syntaxhighlight lang="ada">with Messages; use Messages;
with Ada.Streams.Stream_Io; use Ada.Streams.Stream_Io;
with Ada.Streams.Stream_Io; use Ada.Streams.Stream_Io;
with Ada.Calendar; use Ada.Calendar;
with Ada.Calendar; use Ada.Calendar;
Line 141: Line 141:
end loop;
end loop;
Close(The_File);
Close(The_File);
end Streams_Example;</lang>
end Streams_Example;</syntaxhighlight>
Output results:
Output results:
Time Stamp:2007-3-9
Time Stamp:2007-3-9
Line 165: Line 165:
Serialization in ''ALGOL 68'' is achieved through a technique called
Serialization in ''ALGOL 68'' is achieved through a technique called
''straightening''.
''straightening''.
<lang algol68>MODE ENTITY = STRUCT([6]CHAR name, INT creation);
<syntaxhighlight lang="algol68">MODE ENTITY = STRUCT([6]CHAR name, INT creation);
FORMAT entity repr = $"Name: "g", Created:"g$;
FORMAT entity repr = $"Name: "g", Created:"g$;
MODE PERSON = STRUCT(ENTITY entity, STRING email);
MODE PERSON = STRUCT(ENTITY entity, STRING email);
Line 193: Line 193:
printf((person repr, i1, $l$));
printf((person repr, i1, $l$));
printf((entity repr, i2, $l$))</lang>
printf((entity repr, i2, $l$))</syntaxhighlight>
'''flex'''ible length arrays (including '''string'''s), and tagged-'''union'''
'''flex'''ible length arrays (including '''string'''s), and tagged-'''union'''
types are problematic as the lengths of the arrays, and the ''tag'' of the
types are problematic as the lengths of the arrays, and the ''tag'' of the
Line 212: Line 212:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.IO;
using System.IO;
using System.Collections.Generic;
using System.Collections.Generic;
Line 275: Line 275:
}
}
}
}
}</lang>
}</syntaxhighlight>
<pre>Fido, id=1 is alive
<pre>Fido, id=1 is alive
Lupo, id=2 is alive
Lupo, id=2 is alive
Line 289: Line 289:
compiled with g++ -lboost_serialization serializationtest3.cpp -o serializationtest3
compiled with g++ -lboost_serialization serializationtest3.cpp -o serializationtest3


<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <fstream>
#include <fstream>
#include <boost/serialization/string.hpp>
#include <boost/serialization/string.hpp>
Line 406: Line 406:
w2.print( ) ;
w2.print( ) ;
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>
creating the following output:
creating the following output:
<pre>
<pre>
Line 425: Line 425:
=={{header|Caché ObjectScript}}==
=={{header|Caché ObjectScript}}==


<lang cos>Class Serialize.Employee Extends %SerialObject
<syntaxhighlight lang="cos">Class Serialize.Employee Extends %SerialObject
{
{


Line 450: Line 450:
Property Department As %String [ Private ];
Property Department As %String [ Private ];


}</lang>
}</syntaxhighlight>


<lang cos>Class Serialize.Worker Extends Employee
<syntaxhighlight lang="cos">Class Serialize.Worker Extends Employee
{
{


Line 476: Line 476:
Property HourlyPay As %Numeric [ Private ];
Property HourlyPay As %Numeric [ Private ];


}</lang>
}</syntaxhighlight>


<lang cos>Class Serialize.Example Extends %SerialObject
<syntaxhighlight lang="cos">Class Serialize.Example Extends %SerialObject
{
{


Line 536: Line 536:
Property Workers As list Of Worker;
Property Workers As list Of Worker;


}</lang>
}</syntaxhighlight>


{{out|Examples}}
{{out|Examples}}
Line 561: Line 561:
{{libheader|cl-serializer}}
{{libheader|cl-serializer}}


<lang lisp>(defmacro with-serialization-to-file ((stream pathname) &body body)
<syntaxhighlight lang="lisp">(defmacro with-serialization-to-file ((stream pathname) &body body)
`(with-open-file (,stream ,pathname
`(with-open-file (,stream ,pathname
:element-type '(unsigned-byte 8)
:element-type '(unsigned-byte 8)
Line 572: Line 572:


(defclass person (entity)
(defclass person (entity)
((name :initarg :name :initform "The Nameless One")))</lang>
((name :initarg :name :initform "The Nameless One")))</syntaxhighlight>


And now the REPL log:
And now the REPL log:


<lang lisp>CL-USER> (list (make-instance 'entity)
<syntaxhighlight lang="lisp">CL-USER> (list (make-instance 'entity)
(make-instance 'person))
(make-instance 'person))


Line 610: Line 610:
Slots with :INSTANCE allocation:
Slots with :INSTANCE allocation:
NAME = "The Nameless One"
NAME = "The Nameless One"
(#<ENTITY {1003C12911}> #<PERSON {1003C12A81}>)</lang>
(#<ENTITY {1003C12911}> #<PERSON {1003C12A81}>)</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
Line 628: Line 628:
Run "pbcompiler test.proto" to generate the serializable code. It should generate a D code file named test.d.
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:
In your main file, use the following code:
<lang d>import test1;
<syntaxhighlight lang="d">import test1;
import std.stdio;
import std.stdio;
import std.file;
import std.file;
Line 662: Line 662:
writefln("Output data:");
writefln("Output data:");
base.print;
base.print;
}</lang>
}</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
Line 668: Line 668:
(Inheritance, while supported by various features and patterns, is not a preferred design component in [[E]]; nor are simple record data structures.)
(Inheritance, while supported by various features and patterns, is not a preferred design component in [[E]]; nor are simple record data structures.)


<lang e>def makeEvent(time :int) {
<syntaxhighlight lang="e">def makeEvent(time :int) {
return def event {
return def event {
to __printOn(out) { out.print(`@@$time`) }
to __printOn(out) { out.print(`@@$time`) }
Line 688: Line 688:
to getPosition() { return position }
to getPosition() { return position }
}
}
}</lang>
}</syntaxhighlight>


After defining our data types, we can prepare to serialize them.
After defining our data types, we can prepare to serialize them.


<lang e>def surgeon := <import:org.erights.e.elib.serial.makeSurgeon>().diverge()
<syntaxhighlight lang="e">def surgeon := <import:org.erights.e.elib.serial.makeSurgeon>().diverge()
surgeon.addExit(makeEvent, "makeEvent")
surgeon.addExit(makeEvent, "makeEvent")
surgeon.addExit(makeArrival, "makeArrival")</lang>
surgeon.addExit(makeArrival, "makeArrival")</syntaxhighlight>


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.)
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.)
<lang e>def objs := [makeEvent(timer.now()),
<syntaxhighlight lang="e">def objs := [makeEvent(timer.now()),
makeArrival(timer.now(), "Smith", 7)]
makeArrival(timer.now(), "Smith", 7)]


stdout.println(objs)
stdout.println(objs)
<file:objects.dat>.setBytes(surgeon.serialize(objs))
<file:objects.dat>.setBytes(surgeon.serialize(objs))
stdout.println(surgeon.unserialize(<file:objects.dat>.getBytes()))</lang>
stdout.println(surgeon.unserialize(<file:objects.dat>.getBytes()))</syntaxhighlight>


=={{header|EchoLisp}}==
=={{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.
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.
<lang lisp>
<syntaxhighlight lang="lisp">
(define (person->string self) (format "%a : person." (person-name self)))
(define (person->string self) (format "%a : person." (person-name self)))
(define (writer->string self) (format "%a: writer of %a."
(define (writer->string self) (format "%a: writer of %a."
Line 739: Line 739:
papa → papa: father of (Simon Elvis).
papa → papa: father of (Simon Elvis).
elvis → Elvis : person.
elvis → Elvis : person.
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<lang lisp>
<syntaxhighlight lang="lisp">
;; reboot (close the browser window)
;; reboot (close the browser window)
; inspect objects.dat :
; inspect objects.dat :
Line 770: Line 770:
(define papa (local-get-value 'papa "objects.dat"))
(define papa (local-get-value 'papa "objects.dat"))
papa → papa: father of (Antoinette papa Elvis).
papa → papa: father of (Antoinette papa Elvis).
</syntaxhighlight>
</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==
Erlang is not object oriented. This code is based upon my understanding of the Algol 68 example above.
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 ).
-module( object_serialization ).


Line 803: Line 803:
print( Entity ),
print( Entity ),
io:fwrite( "\temail: ~p~n", [Email] ).
io:fwrite( "\temail: ~p~n", [Email] ).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 818: Line 818:
=={{header|Factor}}==
=={{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.
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.
<lang factor>USING: accessors combinators.extras io io.encodings.binary
<syntaxhighlight lang="factor">USING: accessors combinators.extras io io.encodings.binary
io.files io.files.info kernel prettyprint serialize ;
io.files io.files.info kernel prettyprint serialize ;
IN: rosetta-code.object-serialization
IN: rosetta-code.object-serialization
Line 862: Line 862:
! Print out deserialized objects.
! Print out deserialized objects.


[ . ] tri@</lang>
[ . ] tri@</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 894: Line 894:


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.
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.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,047: Line 1,047:
fmt.Println(" collie, not trained, doesn't catch frisbee")
fmt.Println(" collie, not trained, doesn't catch frisbee")
}
}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>created:
<pre>created:
Line 1,063: Line 1,063:
=={{header|Groovy}}==
=={{header|Groovy}}==
Sample Serializable Classes (borrowed from Java example. Sorta.):
Sample Serializable Classes (borrowed from Java example. Sorta.):
<lang groovy>class Entity implements Serializable {
<syntaxhighlight lang="groovy">class Entity implements Serializable {
static final serialVersionUID = 3504465751164822571L
static final serialVersionUID = 3504465751164822571L
String name = 'Thingamabob'
String name = 'Thingamabob'
Line 1,073: Line 1,073:
Person() { name = 'Clement' }
Person() { name = 'Clement' }
Person(name) { this.name = name }
Person(name) { this.name = name }
}</lang>
}</syntaxhighlight>


Writing objects:
Writing objects:
<lang groovy>File objectStore = new File('objectStore.ser')
<syntaxhighlight lang="groovy">File objectStore = new File('objectStore.ser')
if (objectStore.exists()) { objectStore.delete() }
if (objectStore.exists()) { objectStore.delete() }
assert ! objectStore.exists()
assert ! objectStore.exists()
Line 1,094: Line 1,094:
os << new Person('Schroeder')
os << new Person('Schroeder')
} catch (e) { throw new Exception(e) } finally { os?.close() }
} catch (e) { throw new Exception(e) } finally { os?.close() }
assert objectStore.exists()</lang>
assert objectStore.exists()</syntaxhighlight>


Reading objects:
Reading objects:
<lang groovy>def is
<syntaxhighlight lang="groovy">def is
try {
try {
is = objectStore.newObjectInputStream(this.class.classLoader)
is = objectStore.newObjectInputStream(this.class.classLoader)
Line 1,104: Line 1,104:


objectStore.delete()
objectStore.delete()
assert ! objectStore.exists()</lang>
assert ! objectStore.exists()</syntaxhighlight>


Output:
Output:
Line 1,123: Line 1,123:
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:
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:


<lang haskell>{-# LANGUAGE DeriveGeneric #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE DeriveGeneric #-}


module Main (main) where
module Main (main) where
Line 1,147: Line 1,147:
bytes <- ByteString.readFile "objects.dat"
bytes <- ByteString.readFile "objects.dat"
let employees = Binary.decode bytes
let employees = Binary.decode bytes
print (employees :: [Employee])</lang>
print (employees :: [Employee])</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 1,153: Line 1,153:
This should be sufficient for this task:
This should be sufficient for this task:


<lang j>lin_z_=:5!:5
<syntaxhighlight lang="j">lin_z_=:5!:5
serializeObject=:3 :0
serializeObject=:3 :0
p=. copath y
p=. copath y
Line 1,193: Line 1,193:
print__r1''
print__r1''
print__k1''
print__k1''
print__s1''</lang>
print__s1''</syntaxhighlight>


Here is how the last part looks in action:
Here is how the last part looks in action:


<lang j> print__R''
<syntaxhighlight lang="j"> print__R''
room size small
room size small
print__K''
print__K''
Line 1,213: Line 1,213:
kitchen size medium
kitchen size medium
print__s1''
print__s1''
kitchen with sink size large</lang>
kitchen with sink size large</syntaxhighlight>


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.
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: Line 1,220:


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.io.*;
<syntaxhighlight lang="java">import java.io.*;


// classes must implement java.io.Serializable in order to be serializable
// classes must implement java.io.Serializable in order to be serializable
Line 1,279: Line 1,279:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>
<syntaxhighlight lang="julia">
abstract type Hello end
abstract type Hello end


Line 1,320: Line 1,320:
sayhello(hh1)
sayhello(hh1)
sayhello(hh2)
sayhello(hh2)
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>// version 1.2.0
<syntaxhighlight lang="scala">// version 1.2.0


import java.io.*
import java.io.*
Line 1,380: Line 1,380:
System.exit(1)
System.exit(1)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,393: Line 1,393:


=={{header|Neko}}==
=={{header|Neko}}==
<lang actionscript>/* Object serialization, in Neko */
<syntaxhighlight lang="actionscript">/* Object serialization, in Neko */


var file_open = $loader.loadprim("std@file_open", 2)
var file_open = $loader.loadprim("std@file_open", 2)
Line 1,433: Line 1,433:
var other = unserialize(buff, $loader)
var other = unserialize(buff, $loader)
$print("deserialized:\n")
$print("deserialized:\n")
other.print()</lang>
other.print()</syntaxhighlight>


{{out}}
{{out}}
Line 1,452: Line 1,452:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import marshal, streams
<syntaxhighlight lang="nim">import marshal, streams
type
type
Line 1,477: Line 1,477:
print(t[0])
print(t[0])
print(t[1])
print(t[1])
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,487: Line 1,487:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
bundle Default {
bundle Default {
class Thingy {
class Thingy {
Line 1,538: Line 1,538:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
Line 1,550: Line 1,550:
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).
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).


<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


// a fantasy two level hierarchy
// a fantasy two level hierarchy
Line 1,705: Line 1,705:
}
}
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 1,711: Line 1,711:
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.
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.


<lang ocaml>type entity = { name : string }
<syntaxhighlight lang="ocaml">type entity = { name : string }


let create_entity () = { name = "Entity" }
let create_entity () = { name = "Entity" }
Line 1,733: Line 1,733:


print_entity result1;;
print_entity result1;;
print_entity result2;;</lang>
print_entity result2;;</syntaxhighlight>


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].
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: Line 1,740:
All objects (values and references) can be serialized using `fasl-save` (by `fasl-encode`) and deserialized using `fasl-load` (by `fasl-decode`).
All objects (values and references) can be serialized using `fasl-save` (by `fasl-encode`) and deserialized using `fasl-load` (by `fasl-decode`).


<lang scheme>
<syntaxhighlight lang="scheme">
$ ol
$ ol
Welcome to Otus Lisp 1.2,
Welcome to Otus Lisp 1.2,
Line 1,779: Line 1,779:
bye-bye :/
bye-bye :/
$
$
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
Line 1,790: Line 1,790:
=={{header|Perl}}==
=={{header|Perl}}==
{{libheader|Storable}}
{{libheader|Storable}}
<lang perl>{
<syntaxhighlight lang="perl">{
package Greeting;
package Greeting;
sub new {
sub new {
Line 1,824: Line 1,824:
print $g2->stringify;
print $g2->stringify;
print $s2->stringify;
print $s2->stringify;
};</lang>
};</syntaxhighlight>


{{libheader|MooseX}}
{{libheader|MooseX}}


The same, using [[MooseX]] to serialize to [[uses format::JSON]].
The same, using [[MooseX]] to serialize to [[uses format::JSON]].
<lang perl>use MooseX::Declare;
<syntaxhighlight lang="perl">use MooseX::Declare;


class Greeting {
class Greeting {
Line 1,854: Line 1,854:
print $g2->string;
print $g2->string;
print $s2->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].
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,861: Line 1,861:
or whatever you choose to treat as such, is up to you.
or whatever you choose to treat as such, is up to you.


<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #008000;">"builtins/serialize.e"</span>
<span style="color: #008080;">include</span> <span style="color: #008000;">"builtins/serialize.e"</span>
Line 1,899: Line 1,899:
<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: #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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->


{{out}}
{{out}}
Line 1,914: Line 1,914:
=={{header|PHP}}==
=={{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.
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.
<lang php>$myObj = new Object();
<syntaxhighlight lang="php">$myObj = new Object();
$serializedObj = serialize($myObj);</lang>
$serializedObj = serialize($myObj);</syntaxhighlight>
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.
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,923: Line 1,923:
back. This functionality is also used internally for database access and
back. This functionality is also used internally for database access and
interprocess-communication.
interprocess-communication.
<lang PicoLisp>(class +Point)
<syntaxhighlight lang="picolisp">(class +Point)
# x y
# x y


Line 1,952: Line 1,952:
(out "objects.dat"
(out "objects.dat"
(pr (val P) (getl P))
(pr (val P) (getl P))
(pr (val C) (getl C)) )</lang>
(pr (val C) (getl C)) )</syntaxhighlight>
<lang PicoLisp>(in "objects.dat"
<syntaxhighlight lang="picolisp">(in "objects.dat"
(putl (setq A (box (rd))) (rd))
(putl (setq A (box (rd))) (rd))
(putl (setq B (box (rd))) (rd)) )
(putl (setq B (box (rd))) (rd)) )


(print> A)
(print> A)
(print> B)</lang>
(print> B)</syntaxhighlight>
Output:
Output:
<pre>Point 3,4
<pre>Point 3,4
Line 1,966: Line 1,966:


=={{header|Python}}==
=={{header|Python}}==
<lang python># Object Serialization in Python
<syntaxhighlight lang="python"># Object Serialization in Python
# serialization in python is accomplished via the Pickle module.
# serialization in python is accomplished via the Pickle module.
# Alternatively, one can use the cPickle module if speed is the key,
# Alternatively, one can use the cPickle module if speed is the key,
Line 2,002: Line 2,002:


i1.printName()
i1.printName()
i2.printName()</lang>
i2.printName()</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 2,009: Line 2,009:


The serialization needs to be included with
The serialization needs to be included with
<lang racket>(require racket/serialize)</lang>
<syntaxhighlight lang="racket">(require racket/serialize)</syntaxhighlight>
The rest is covered by the Racket language.
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)
(I have elided the paths in objects.dat -- you wouldn't be able to use them anyway)


<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
;; Object Serialization: Tim Brown, Oct. 2014
;; Object Serialization: Tim Brown, Oct. 2014
(require racket/serialize)
(require racket/serialize)
Line 2,085: Line 2,085:
(printf "With siblings:\t~s (he hasn't any)~%" (send cloned-john ->string #:show '(siblings)))
(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 children:\t~s~%" (send cloned-john ->string #:show '(children)))
(printf "With both:\t~s~%" (send cloned-john ->string #:show '(siblings children)))</lang>
(printf "With both:\t~s~%" (send cloned-john ->string #:show '(siblings children)))</syntaxhighlight>


{{out}}
{{out}}
Line 2,113: Line 2,113:
=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6># Reference:
<syntaxhighlight lang="raku" line># Reference:
# https://docs.raku.org/language/classtut
# https://docs.raku.org/language/classtut
# https://github.com/teodozjan/perl-store
# https://github.com/teodozjan/perl-store
Line 2,146: Line 2,146:
my $r2 = from_file('objects.dat');
my $r2 = from_file('objects.dat');
say "Rectangle2 is of type ", $r2.WHAT;
say "Rectangle2 is of type ", $r2.WHAT;
say "Rectangle2 area is ", $r2.area();</lang>
say "Rectangle2 area is ", $r2.area();</syntaxhighlight>
{{out}}
{{out}}
<pre>Create Rectangle1 with area 100
<pre>Create Rectangle1 with area 100
Line 2,161: Line 2,161:
=={{header|Ruby}}==
=={{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.
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.
<lang ruby>class Being
<syntaxhighlight lang="ruby">class Being
def initialize(specialty=nil)
def initialize(specialty=nil)
@specialty=specialty
@specialty=specialty
Line 2,230: Line 2,230:
end.join("\n\n")
end.join("\n\n")
)
)
puts "END LOADED DIVERSE COLLECTION"</lang>
puts "END LOADED DIVERSE COLLECTION"</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Line 2,236: Line 2,236:
=== Enum ===
=== Enum ===
Dependencies:
Dependencies:
<lang TOML>serde = { version = "1.0.89", features = ["derive"] }
<syntaxhighlight lang="toml">serde = { version = "1.0.89", features = ["derive"] }
bincode = "1.1.2"</lang>
bincode = "1.1.2"</syntaxhighlight>


<lang Rust>use std::fmt;
<syntaxhighlight lang="rust">use std::fmt;


use bincode::{deserialize, serialize};
use bincode::{deserialize, serialize};
Line 2,286: Line 2,286:


Ok(())
Ok(())
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Rover is a dog with brown fur
<pre>Rover is a dog with brown fur
Line 2,303: Line 2,303:
=== Trait ===
=== Trait ===
Dependencies:
Dependencies:
<lang TOML>serde = { version = "1.0.89", features = ["derive"] }
<syntaxhighlight lang="toml">serde = { version = "1.0.89", features = ["derive"] }
bincode = "1.1.2"
bincode = "1.1.2"
typetag = "0.1.1"</lang>
typetag = "0.1.1"</syntaxhighlight>


<lang Rust>use std::fmt::{self, Debug, Display};
<syntaxhighlight lang="rust">use std::fmt::{self, Debug, Display};


use bincode::{deserialize, serialize};
use bincode::{deserialize, serialize};
Line 2,392: Line 2,392:


Ok(())
Ok(())
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Rover is a dog with brown fur
<pre>Rover is a dog with brown fur
Line 2,411: Line 2,411:
{{works with|Tcl|8.6}}
{{works with|Tcl|8.6}}
''This example uses an experimental package, available from [http://wiki.tcl.tk/23444 The Tcler's Wiki].
''This example uses an experimental package, available from [http://wiki.tcl.tk/23444 The Tcler's Wiki].
<lang tcl>package require Tcl 8.6
<syntaxhighlight lang="tcl">package require Tcl 8.6
package require TclOO::serializer 0.1
package require TclOO::serializer 0.1


Line 2,462: Line 2,462:
set obj [oo::deserialize [read $f]]
set obj [oo::deserialize [read $f]]
close $f
close $f
$obj printGreetings</lang>
$obj printGreetings</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-json}}
{{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.
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.
<lang ecmascript>import "/json" for JSON
<syntaxhighlight lang="ecmascript">import "/json" for JSON
import "io" for File, FileFlags
import "io" for File, FileFlags


Line 2,527: Line 2,527:


System.print("\nContents of objects.dat are:")
System.print("\nContents of objects.dat are:")
System.print(File.read(fileName))</lang>
System.print(File.read(fileName))</syntaxhighlight>


{{out}}
{{out}}
Line 2,543: Line 2,543:
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 ...
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 ...


<lang zkl>class [static] ARootClass{ // A top level class, no instances
<syntaxhighlight lang="zkl">class [static] ARootClass{ // A top level class, no instances
class A{ self.println(" constructor"); } // a regular class
class A{ self.println(" constructor"); } // a regular class
class B(A){ // ditto
class B(A){ // ditto
Line 2,568: Line 2,568:
rc.B().println(); // create a new instance of B
rc.B().println(); // create a new instance of B
// prints:
// prints:
x is 123</lang>
x is 123</syntaxhighlight>