diff --git a/serde/json/deserializer.nim b/serde/json/deserializer.nim index 72e5181..de7b620 100644 --- a/serde/json/deserializer.nim +++ b/serde/json/deserializer.nim @@ -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) diff --git a/tests/json/testDeserialize.nim b/tests/json/testDeserialize.nim index a17fdb9..56e860a 100644 --- a/tests/json/testDeserialize.nim +++ b/tests/json/testDeserialize.nim @@ -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