Skip to content

Instantly share code, notes, and snippets.

@lkebin
Last active May 13, 2019 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lkebin/fbebdfe334a0c05a1f543b1f4137fec6 to your computer and use it in GitHub Desktop.
Save lkebin/fbebdfe334a0c05a1f543b1f4137fec6 to your computer and use it in GitHub Desktop.
Golang Customized UnmarshalJSON Use Case https://play.golang.org/p/HwYr3Pm6hg_P
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