-
Notifications
You must be signed in to change notification settings - Fork 9
/
unmarshal_example_test.go
68 lines (54 loc) · 1.57 KB
/
unmarshal_example_test.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
package jsonapi_test
import (
"fmt"
"github.com/DataDog/jsonapi"
)
func ExampleUnmarshal() {
body := `{"data":{"id":"1","type":"articles","attributes":{"title":"Hello World"}}}`
type Article struct {
ID string `jsonapi:"primary,articles"`
Title string `jsonapi:"attribute" json:"title"`
}
var a Article
err := jsonapi.Unmarshal([]byte(body), &a)
if err != nil {
panic(err)
}
fmt.Printf("%+v", &a)
// Output: &{ID:1 Title:Hello World}
}
func ExampleUnmarshal_slice() {
body := `{"data":[{"id":"1","type":"articles","attributes":{"title":"Hello World"}},{"id":"2","type":"articles","attributes":{"title":"Hello Again"}}]}`
type Article struct {
ID string `jsonapi:"primary,articles"`
Title string `jsonapi:"attribute" json:"title"`
}
var a []*Article
err := jsonapi.Unmarshal([]byte(body), &a)
if err != nil {
panic(err)
}
fmt.Printf("%+v %+v", a[0], a[1])
// Output: &{ID:1 Title:Hello World} &{ID:2 Title:Hello Again}
}
func ExampleUnmarshalMeta() {
body := `{"data":{"id":"1","type":"articles","attributes":{"title":"Hello World"},"meta":{"views":10}},"meta":{"foo":"bar"}}`
type ArticleMeta struct {
Views int `json:"views"`
}
type Article struct {
ID string `jsonapi:"primary,articles"`
Title string `jsonapi:"attribute" json:"title"`
Meta *ArticleMeta `jsonapi:"meta"`
}
var (
a Article
m map[string]any
)
err := jsonapi.Unmarshal([]byte(body), &a, jsonapi.UnmarshalMeta(&m))
if err != nil {
panic(err)
}
fmt.Printf("%s %s %+v %+v", a.ID, a.Title, a.Meta, m)
// Output: 1 Hello World &{Views:10} map[foo:bar]
}