-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomUnmarshalJSON.go
67 lines (54 loc) · 1.5 KB
/
CustomUnmarshalJSON.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
type response struct {
Album string `json:"album"`
Title string
Year string
Downloads string
}
type responseWrapper struct {
response
}
func (r *responseWrapper) UnmarshalJSON(b []byte) (err error) {
// Parse the raw data into a map for custom handling
var raw map[string]interface{}
// First unmarshal into r.response (assuming it's for storing the raw response)
if err := json.Unmarshal(b, &r.response); err != nil {
return err // Return the error if unmarshalling fails
}
// Now unmarshal into the raw map
if err := json.Unmarshal(b, &raw); err != nil {
return err // Return the error if unmarshalling fails
}
fmt.Println("Hello")
// Switch based on r.Item to parse different structures
switch r.Album {
case "song":
if inner, ok := raw["song"].(map[string]interface{}); ok {
if title, ok := inner["title"].(string); ok {
r.Title = title
}
}
if inner, ok := raw["song"].(map[string]interface{}); ok {
if year, ok := inner["year"].(string); ok {
r.Year = year
}
}
if inner, ok := raw["song"].(map[string]interface{}); ok {
if dw, ok := inner["downloads"].(string); ok {
r.Downloads = dw
}
}
}
return nil // Return nil if everything is successful
}
func main() {
var resp1 responseWrapper
var err error
data := `{
"album":"song",
"song":{ "title":"Happy trails","year":"2232", "downloads":"21222222"}
}`
if err = json.Unmarshal([]byte(data), &resp1); err != nil {
fmt.Printf("%#v\n", err)
}
fmt.Printf("%#v\n", resp1.response)
}