status-im / nim-serialization

A modern and extensible serialization framework for Nim
62 stars 8 forks source link

Support for inheritance #26

Closed emizzle closed 4 years ago

emizzle commented 4 years ago

When trying to de/serialize an object that inherits from another type, an error is thrown.

Setup

import json_serialization

type Signal* = ref object of RootObj
  signalType*: string

type NodeSignal* = ref object of Signal
  event*: string

Serialize

var signal = NodeSignal(signalType: "node.started", event: "this happened")

signal.toJson
# throws error "Error: The type NodeSignal:ObjectType doesn't have a field named signalType"

Expected result: signal.toJson should serialize to "{\"signalType\":\"node.started\", \"event\":\"this happened\"}"

Deserialize

discard Json.decode("{\"signalType\":\"node.started\", \"event\":\"this happened\"}", NodeSignal)
# throws:
# /Users/emizzle/.nimble/pkgs/serialization-0.1.0/serialization.nim(63) no_inheritance
# /Users/emizzle/.nimble/pkgs/serialization-0.1.0/serialization.nim(45) readValue
# /Users/emizzle/.nimble/pkgs/json_serialization-0.1.0/json_serialization/reader.nim(218) readValue
# /Users/emizzle/.nimble/pkgs/serialization-0.1.0/serialization.nim(45) readValue
# /Users/emizzle/.nimble/pkgs/json_serialization-0.1.0/json_serialization/reader.nim(305) readValue
# /Users/emizzle/.nimble/pkgs/json_serialization-0.1.0/json_serialization/reader.nim(89) raiseUnexpectedField
# Error: unhandled exception:  [UnexpectedField]
# Error: execution of an external program failed: '/Users/emizzle/temp/json-ser-test/json_ser_test/src/no_inheritance '

Expected result: the result of Json.decode should deserialize to

NodeSignal:
  signalType: "node.started"
  event: "this happened"
zah commented 4 years ago

This has been implemented through improvements in nim-stew: https://github.com/status-im/nim-stew/pull/40

Just pull the latest version of nim-stew, no changes are required in nim-serialization or nim-json-serialization.