Skip to content

Commit

Permalink
deserialize seq[T] and Option[T] from string (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
emizzle authored Feb 14, 2024
1 parent 1af86f8 commit e67f7e4
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
8 changes: 8 additions & 0 deletions serde/json/deserializer.nim
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,11 @@ proc fromJson*[T: ref object or object](_: type T, bytes: openArray[byte]): ?!T
proc fromJson*[T: ref object or object](_: type T, json: string): ?!T =
let jsn = ?JsonNode.parse(json) # full qualification required in-module only
T.fromJson(jsn)

proc fromJson*[T: ref object or object](_: type seq[T], json: string): ?!seq[T] =
let jsn = ?JsonNode.parse(json) # full qualification required in-module only
seq[T].fromJson(jsn)

proc fromJson*[T: ref object or object](_: type ?T, json: string): ?!Option[T] =
let jsn = ?JsonNode.parse(json) # full qualification required in-module only
Option[T].fromJson(jsn)
56 changes: 56 additions & 0 deletions tests/json/testDeserialize.nim
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,59 @@ suite "json serialization - deserialize":
let deserialized = !MyRef.fromJson(byteArray)
check deserialized.mystring == expected.mystring
check deserialized.myint == expected.myint

suite "deserialize from string":

test "deserializes objects from string":
type MyObj = object
mystring: string
myint: int

let expected = MyObj(mystring: "abc", myint: 1)
let myObjJson = """{
"mystring": "abc",
"myint": 1
}"""

check !MyObj.fromJson(myObjJson) == expected

test "deserializes ref objects from string":
type MyRef = ref object
mystring: string
myint: int

let expected = MyRef(mystring: "abc", myint: 1)
let myRefJson = """{
"mystring": "abc",
"myint": 1
}"""

let deserialized = !MyRef.fromJson(myRefJson)
check deserialized.mystring == expected.mystring
check deserialized.myint == expected.myint

test "deserializes seq[T] from string":
type MyObj = object
mystring: string
myint: int

let expected = @[MyObj(mystring: "abc", myint: 1)]
let myObjsJson = """[{
"mystring": "abc",
"myint": 1
}]"""

check !seq[MyObj].fromJson(myObjsJson) == expected

test "deserializes Option[T] from string":
type MyObj = object
mystring: string
myint: int

let expected = some MyObj(mystring: "abc", myint: 1)
let myObjJson = """{
"mystring": "abc",
"myint": 1
}"""

check !(Option[MyObj].fromJson(myObjJson)) == expected

0 comments on commit e67f7e4

Please sign in to comment.