Source Edit

This module contains procs for serialization and deserialization of arbitrary Nim data structures. The serialization format uses JSON.

Restriction: For objects, their type is not serialized. This means essentially that it does not work if the object has some other runtime type than its compiletime type.

Basic usage

Example:

  1. import std/marshal
  2. type
  3. A = object of RootObj
  4. B = object of A
  5. f: int
  6. let a: ref A = new(B)
  7. assert $$a[] == "{}" # not "{f: 0}"
  8. # unmarshal
  9. let c = to[B]("""{"f": 2}""")
  10. assert typeof(c) is B
  11. assert c.f == 2
  12. # marshal
  13. assert $$c == """{"f": 2}"""

Note: The to and $$ operations are available at compile-time!

See also

Imports

streams, typeinfo, json, intsets, tables, unicode

Procs

  1. proc `$$`[T](x: sink T): string

Returns a string representation of x (serialization, marshalling).

Note: to serialize x to JSON use %x from the json module or jsonutils.toJson(x).

Example:

  1. type
  2. Foo = object
  3. id: int
  4. bar: string
  5. let x = Foo(id: 1, bar: "baz")
  6. ## serialize:
  7. let y = $$x
  8. assert y == """{"id": 1, "bar": "baz"}"""

Source Edit

  1. proc load[T](s: Stream; data: var T)

Loads data from the stream s. Raises IOError in case of an error.

Example:

  1. import std/streams
  2. var s = newStringStream("[1, 3, 5]")
  3. var a: array[3, int]
  4. load(s, a)
  5. assert a == [1, 3, 5]

Source Edit

  1. proc store[T](s: Stream; data: sink T)

Stores data into the stream s. Raises IOError in case of an error.

Example:

  1. import std/streams
  2. var s = newStringStream("")
  3. var a = [1, 3, 5]
  4. store(s, a)
  5. s.setPosition(0)
  6. assert s.readAll() == "[1, 3, 5]"

Source Edit

  1. proc to[T](data: string): T

Reads data and transforms it to a type T (deserialization, unmarshalling).

Example:

  1. type
  2. Foo = object
  3. id: int
  4. bar: string
  5. let y = """{"id": 1, "bar": "baz"}"""
  6. assert typeof(y) is string
  7. ## deserialize to type 'Foo':
  8. let z = y.to[:Foo]
  9. assert typeof(z) is Foo
  10. assert z.id == 1
  11. assert z.bar == "baz"

Source Edit