blob: a4d1f81a87cefdc90031100e257fa360e6cb2575 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"os"
)
type Optional[T any] struct {
Value T
Exists bool
}
func (o *Optional[T]) UnmarshalJSON(data []byte) error {
var Temp *T
err := json.Unmarshal(data, &Temp)
if err != nil {
return err
}
if Temp == nil {
var empty T
o.Value = empty
o.Exists = false
return nil
}
o.Value = *Temp
o.Exists = true
return nil
}
func (o Optional[T]) MarshalJSON() ([]byte, error) {
var Temp *T
if o.Exists {
Temp = &o.Value
}
return json.Marshal(Temp)
}
type Testy struct {
Flag Optional[bool] `json:"flag"`
Cake Optional[[]int] `json:"cake"`
Opt Optional[string] `json:"opt"`
}
const TEXT = `{
"cake": [],
"opt": null
}`
const TEMPLATE = `Flag is: {{if .Flag.Exists}}{{.Flag.Value}}{{else}}[none]{{end}}
Cake is: {{if .Cake.Exists}}{{range .Cake.Value}}{{.}} {{end}}{{else}}[none]{{end}}
Opt is: {{if .Opt.Exists}}{{.Opt.Value}}{{else}}[none]{{end}}
`
func main() {
var t Testy
json.Unmarshal([]byte(TEXT), &t)
tmpl, err := template.New("mytemplate").Parse(TEMPLATE)
if err != nil {
log.Fatal(err)
}
tmpl.Execute(os.Stdout, t)
b, err := json.Marshal(t)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
}
|