Skip to content

Commit 6c0c3cf

Browse files
authored
Merge pull request #10 from i-Naji/dev
add renameHook while looking for the discriminatorFieldName
2 parents 907bd3c + 202f45f commit 6c0c3cf

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/jsony.nim

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,8 @@ proc parseHook*[T: object|ref object](s: string, i: var int, v: var T) =
301301
var key: string
302302
parseHook(s, i, key)
303303
eatChar(s, i, ':')
304+
when compiles(renameHook(v, key)):
305+
renameHook(v, key)
304306
if key == v.discriminatorFieldName:
305307
var discriminator: type(v.discriminatorField)
306308
parseHook(s, i, discriminator)

tests/test_objects.nim

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,3 +228,42 @@ block:
228228
doAssertRaises JsonError:
229229
let
230230
a = """{"active":true,"floatVal":3.14}""".fromJson(ValueNode)
231+
232+
type
233+
NodeNumKind = enum # the different node types
234+
nkInt, # a leaf with an integer value
235+
nkFloat, # a leaf with a float value
236+
RefNode = ref object
237+
active: bool
238+
case kind: NodeNumKind # the ``kind`` field is the discriminator
239+
of nkInt: intVal: int
240+
of nkFloat: floatVal: float
241+
ValueNode = object
242+
active: bool
243+
case kind: NodeNumKind # the ``kind`` field is the discriminator
244+
of nkInt: intVal: int
245+
of nkFloat: floatVal: float
246+
247+
proc renameHook*(v: var RefNode|ValueNode, fieldName: var string) =
248+
# rename``type`` field name to ``kind``
249+
if fieldName == "type":
250+
fieldName = "kind"
251+
252+
# Test renameHook and discriminator Field Name not being first.
253+
block:
254+
let
255+
a = """{"active":true,"type":"nkFloat","floatVal":3.14}""".fromJson(RefNode)
256+
b = """{"floatVal":3.14,"active":true,"type":"nkFloat"}""".fromJson(RefNode)
257+
c = """{"type":"nkFloat","floatVal":3.14,"active":true}""".fromJson(RefNode)
258+
doAssert a.kind == nkFloat
259+
doAssert b.kind == nkFloat
260+
doAssert c.kind == nkFloat
261+
262+
block:
263+
let
264+
a = """{"active":true,"type":"nkFloat","floatVal":3.14}""".fromJson(ValueNode)
265+
b = """{"floatVal":3.14,"active":true,"type":"nkFloat"}""".fromJson(ValueNode)
266+
c = """{"type":"nkFloat","floatVal":3.14,"active":true}""".fromJson(ValueNode)
267+
doAssert a.kind == nkFloat
268+
doAssert b.kind == nkFloat
269+
doAssert c.kind == nkFloat

0 commit comments

Comments
 (0)