-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
69 lines (54 loc) · 1.1 KB
/
main.go
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
package main
import (
"fmt"
"os"
"github.com/go-json-experiment/json"
"github.com/go-json-experiment/json/jsontext"
)
func main() {
data := []byte(`[
{ "width": 5 },
{ "height": 10 },
{ "name": "example" }
]`)
var attrs []Attr
opts := json.WithUnmarshalers(json.UnmarshalFuncV2(unmarshalAttr))
err := json.Unmarshal(data, &attrs, opts)
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
fmt.Println(attrs)
}
func unmarshalAttr(dec *jsontext.Decoder, v *Attr, opts json.Options) error {
var proxy struct {
Width *int `json:"width"`
Height *int `json:"height"`
Name *string `json:"name"`
}
err := json.UnmarshalDecode(dec, &proxy)
if err != nil {
return err
}
switch {
case proxy.Width != nil:
*v = Width(*proxy.Width)
case proxy.Height != nil:
*v = Height(*proxy.Height)
case proxy.Name != nil:
*v = Name(*proxy.Name)
}
return nil
}
type Attr interface {
isAttr()
}
type Width int
func (Width) isAttr() {}
type Height int
func (Height) isAttr() {}
type Name string
func (Name) isAttr() {}
func (n Name) String() string {
return string(n)
}