mirror of
https://github.com/logos-storage/nim-serde.git
synced 2026-01-02 13:43:06 +00:00
deserialize seq[T] and Option[T] from string (#9)
This commit is contained in:
parent
1af86f84dc
commit
e67f7e4b04
@ -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)
|
||||
|
||||
@ -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
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user