summaryrefslogtreecommitdiff
path: root/optional/json.go
diff options
context:
space:
mode:
authorxengineering <me@xengineering.eu>2024-11-08 18:21:09 +0100
committerxengineering <me@xengineering.eu>2024-11-08 18:21:09 +0100
commitd8dbdaedcfb9099ae091a805972d380a7cddc4a4 (patch)
treeed5965bcdeed0c395604a7a46095d8c09a0f396b /optional/json.go
parent08ea24952ece9c82a932910126975d26e486758c (diff)
downloadoptional-go-d8dbdaedcfb9099ae091a805972d380a7cddc4a4.tar
optional-go-d8dbdaedcfb9099ae091a805972d380a7cddc4a4.tar.zst
optional-go-d8dbdaedcfb9099ae091a805972d380a7cddc4a4.zip
Add json (un)marshal supportv1.0.0
This allows to use optionals for fields of structs which are marshalled or unmarshalled to or from JavaScript object notation (JSON).
Diffstat (limited to 'optional/json.go')
-rw-r--r--optional/json.go35
1 files changed, 35 insertions, 0 deletions
diff --git a/optional/json.go b/optional/json.go
new file mode 100644
index 0000000..23aa780
--- /dev/null
+++ b/optional/json.go
@@ -0,0 +1,35 @@
+package optional
+
+import (
+ "encoding/json"
+)
+
+func (o *Optional[T]) UnmarshalJSON(data []byte) error {
+ var Buffer *T
+
+ err := json.Unmarshal(data, &Buffer)
+ if err != nil {
+ return err
+ }
+
+ if Buffer == nil {
+ var empty T
+ o.Value = empty
+ o.Exists = false
+ return nil
+ }
+
+ o.Value = *Buffer
+ o.Exists = true
+ return nil
+}
+
+func (o Optional[T]) MarshalJSON() ([]byte, error) {
+ var Buffer *T
+
+ if o.Exists {
+ Buffer = &o.Value
+ }
+
+ return json.Marshal(Buffer)
+}