Last active
May 13, 2019 07:31
-
-
Save lkebin/fbebdfe334a0c05a1f543b1f4137fec6 to your computer and use it in GitHub Desktop.
Golang Customized UnmarshalJSON Use Case https://play.golang.org/p/HwYr3Pm6hg_P
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
type Picture string | |
type Profile struct { | |
ID string `json:"id"` | |
FirstName string `json:"first_name"` | |
LastName string `json:"last_name"` | |
Name string `json:"name"` | |
Picture Picture `json:"picture,omitempty"` | |
} | |
func (p *Picture) UnmarshalJSON(b []byte) error { | |
var pictureData struct { | |
Data struct { | |
Url string `json:"url"` | |
} `json:"data"` | |
} | |
if err := json.Unmarshal(b, &pictureData); err != nil { | |
return err | |
} | |
*p = Picture(pictureData.Data.Url) | |
return nil | |
} | |
func main() { | |
var j string = `{ | |
"name": "Kebin Liu", | |
"first_name": "Kebin", | |
"last_name": "Liu", | |
"picture": { | |
"data": { | |
"url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid= 123456789&height=200&width=200&ext=1560322969&hash=AeQE-Oiml5D2s-2d" | |
} | |
}, | |
"id": "123456789" | |
}` | |
var profile Profile | |
json.Unmarshal([]byte(j), &profile) | |
fmt.Println(profile) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment