Fix deserialization of openArray[byte] (#2)

This commit is contained in:
Eric 2024-02-09 10:33:14 +11:00 committed by GitHub
parent d113c1e158
commit 1b77afcbf1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 22 additions and 4 deletions

View File

@ -229,13 +229,15 @@ proc fromJson*[T: ref object or object](_: type T, json: JsonNode): ?!T =
success(res)
proc fromJson*[T: ref object or object](_: type T, bytes: seq[byte]): ?!T =
let json = ?parse(string.fromBytes(bytes))
T.fromJson(json)
proc fromJson*(_: type JsonNode, jsn: string): ?!JsonNode =
return parser.parseJson(jsn)
proc fromJson*[T: ref object or object](_: type T, bytes: openArray[byte]): ?!T =
let json = string.fromBytes(bytes)
static:
echo "typeof json after parse: ", typeof json
T.fromJson(json)
proc fromJson*[T: ref object or object](_: type T, jsn: string): ?!T =
let jsn = ?parser.parseJson(jsn) # full qualification required in-module only
T.fromJson(jsn)

View File

@ -3,6 +3,7 @@ import std/options
import std/unittest
import pkg/stint
import pkg/serde
import pkg/stew/byteutils
import pkg/questionable
import pkg/questionable/results
@ -137,3 +138,18 @@ suite "json serialization - deserialize":
let deserialized = !MyRef.fromJson(json)
check deserialized.mystring == expected.mystring
check deserialized.myint == expected.myint
test "deserializes openArray[byte]":
type MyRef = ref object
mystring: string
myint: int
let expected = MyRef(mystring: "abc", myint: 1)
let byteArray = """{
"mystring": "abc",
"myint": 1
}""".toBytes
let deserialized = !MyRef.fromJson(byteArray)
check deserialized.mystring == expected.mystring
check deserialized.myint == expected.myint