Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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