Skip to content

Instantly share code, notes, and snippets.

@sujamess
Last active August 4, 2021 14:02
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 sujamess/10087f77db7806ff2e0af83cc8e8d92e to your computer and use it in GitHub Desktop.
Save sujamess/10087f77db7806ff2e0af83cc8e8d92e to your computer and use it in GitHub Desktop.
Custom Unmarshal
package main
import (
"encoding/json"
"fmt"
"strings"
)
// 1st Implementation
type Blog1 struct {
ThumbnailURL string `json:"thumbnailUrl"`
Title string `json:"title"`
Tags Tags `json:"tags"`
}
type Tags []string
func (t *Tags) UnmarshalJSON(data []byte) error {
var tags string
err := json.Unmarshal(data, &tags)
if err != nil {
return err
}
*t = strings.Split(tags, ", ")
return nil
}
// 2nd Implementation
type Blog2 struct {
ThumbnailURL string `json:"thumbnailUrl"`
Title string `json:"title"`
Tags []string `json:"tags"`
}
func (b *Blog2) UnmarshalJSON(data []byte) error {
type blog struct {
ThumbnailURL string `json:"thumbnailUrl"`
Title string `json:"title"`
Tags string `json:"tags"`
}
var blg blog
err := json.Unmarshal(data, &blg)
if err != nil {
return err
}
b.ThumbnailURL = blg.ThumbnailURL
b.Title = blg.Title
b.Tags = strings.Split(blg.Tags, ", ")
return nil
}
func main() {
blogJSON := `{"thumbnailUrl": "https://assets.sujames.com/blogs/511a21c4-c923-42fd-996a-10c7ca114f77", "title": "ทำ Custom Unmarshal ใน Go กันเถอะ!", "tags": "Golang, Custom Unmarshal, JSON"}`
err := unmarshalBlog1([]byte(blogJSON))
if err != nil {
// handle error
}
err = unmarshalBlog2([]byte(blogJSON))
if err != nil {
// handle error
}
}
func unmarshalBlog1(blogJSON []byte) error {
var b Blog1
err := json.Unmarshal(blogJSON, &b)
if err != nil {
return err
}
for i, t := range b.Tags {
fmt.Printf("[blog1] at index %d: %s\n", i, t)
}
return nil
}
func unmarshalBlog2(blogJSON []byte) error {
var b Blog2
err := json.Unmarshal(blogJSON, &b)
if err != nil {
return err
}
for i, t := range b.Tags {
fmt.Printf("[blog2] at index %d: %s\n", i, t)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment