# marshal

- マニュアル
- 標準ライブラリ
- 索引

検索
分類:

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.

# 基本の用法

    type
      A = object of RootObj
      B = object of A
        f: int

    var
      a: ref A
      b: ref B

    new(b)
    a = b
    echo($$a[]) # produces "{}", not "{f: 0}"

    # unmarshal
    let c = to[B]("""{"f": 2}""")
    assert typeof(c) is B
    assert c.f == 2

    # marshal
    let s = $$c
    assert s == """{"f": 2}"""

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

# 関連

- streams module
- json module

# インポート

streams, typeinfo, json, intsets, tables, unicode

# プロシージャ

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

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

  用例:

      import
        marshal, streams

      var s = newStringStream("[1, 3, 5]")
      var a: array[3, int]
      load(s, a)
      assert a == [1, 3, 5]

  ソース 編集

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

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

  用例:

      import
        marshal, streams

      var s = newStringStream("")
      var a = [1, 3, 5]
      store(s, a)
      s.setPosition(0)
      assert s.readAll() == "[1, 3, 5]"

  ソース 編集

    proc `$$`[T](x: T): string

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

  Note: to serialize `x` to JSON use `$(%x)` from the `json` module.

  用例:

      type
        Foo = object
          id: int
          bar: string

      let x = Foo(id: 1, bar: "baz")
      ## serialize:
      let y = $$x
      assert y == """{"id": 1, "bar": "baz"}"""

  ソース 編集

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

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

  用例:

      type
        Foo = object
          id: int
          bar: string

      let y = """{"id": 1, "bar": "baz"}"""
      assert typeof(y) is string
      ## deserialize to type 'Foo':
      let z = to[Foo](y)
      assert typeof(z) is Foo
      assert z.id == 1
      assert z.bar == "baz"

  ソース 編集