File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -48,6 +48,45 @@ test.data.If(func(s string) {
4848})
4949```
5050
51+ ## Marshalling/Unmarshalling JSON
52+
53+ Optional types also marshal to/from JSON as you would expect:
54+
55+ ### Marshalling
56+
57+ ``` go
58+ func main () {
59+ var value = struct {
60+ Field optional.String ` json:"field,omitempty"`
61+ }{
62+ Field: optional.NewString (" bar" ),
63+ }
64+
65+ out , _ := json.Marshal (value)
66+ fmt.Println (string (out))
67+ // outputs: {"field":"bar"}
68+ }
69+ ```
70+
71+ ### Unmarshalling
72+
73+ ``` go
74+ func main () {
75+ var value = &struct {
76+ Field optional.String ` json:"field,omitempty"`
77+ }{}
78+
79+ _ = json.Unmarshal ([]byte (` {"field":"bar"}` ), value)
80+
81+ value.Field .If (func (s string ) {
82+ fmt.Println (s)
83+ })
84+ // outputs: bar
85+ }
86+ ```
87+
88+ See [ example_test.go] ( example_test.go ) for more examples.
89+
5190## Inspiration
5291
5392* Java [ Optional] ( https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html )
@@ -113,9 +152,9 @@ and output file is optional_t.go. This can be overridden with the -output flag.
113152
114153``` go
115154import (
116- " fmt"
155+ " fmt"
117156
118- " github.com/markphelps/optional"
157+ " github.com/markphelps/optional"
119158)
120159
121160s := optional.NewString (" foo" )
You can’t perform that action at this time.
0 commit comments