From bcabc173d4103f33baa67407314ec9000315ce54 Mon Sep 17 00:00:00 2001 From: Eric <5089238+emizzle@users.noreply.github.com> Date: Thu, 8 Feb 2024 12:11:19 +1100 Subject: [PATCH] Add overloading examples to README --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index 77da4f4..0882d3f 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,27 @@ assert res.error of SerdeError assert res.error.msg == "json field(s) missing in object: {\"extra\"}" ``` +## Custom types + +If `serde` can't de/serialize a custom type, de/serialization can be supported by +overloading `%` and `fromJson`. For example: + +```nim +type + Address* = distinct array[20, byte] + SerializationError* = object of CatchableError + +func `%`*(address: Address): JsonNode = + %($address) + +func fromJson(_: type Address, json: JsonNode): ?!Address = + expectJsonKind(Address, JString, json) + without address =? Address.init(json.getStr), error: + return failure newException(SerializationError, + "Failed to convert '" & $json & "' to Address: " & error.msg) + success address +``` + ## Serializing to string (`toJson`) `toJson` is a shortcut for serializing an object into its serialized string representation: