Skip to content

Instantly share code, notes, and snippets.

@apoorvmote
Created February 23, 2021 08:54
Show Gist options
  • Save apoorvmote/045b908b1db3eecf6349842b882bc590 to your computer and use it in GitHub Desktop.
Save apoorvmote/045b908b1db3eecf6349842b882bc590 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
)
// OptionalInt is for json unmarshal
type OptionalInt struct {
Value int
isValid bool
isSet bool
}
// User is user props
type User struct {
Views OptionalInt `json:"views"`
}
func main() {
body1 := `{"views": 5}`
body2 := `{"views": null}`
body3 := `{"age": 5}`
var currentUser1 User
if err := json.Unmarshal([]byte(body1), &currentUser1); err != nil {
fmt.Println(err)
}
fmt.Printf("isSet: %v, isValid: %v, value: %v\n", currentUser1.Views.isSet, currentUser1.Views.isValid, currentUser1.Views.Value)
var currentUser2 User
if err := json.Unmarshal([]byte(body2), &currentUser2); err != nil {
fmt.Println(err)
}
fmt.Printf("isSet: %v, isValid: %v, value: %v\n", currentUser2.Views.isSet, currentUser2.Views.isValid, currentUser2.Views.Value)
var currentUser3 User
if err := json.Unmarshal([]byte(body3), &currentUser3); err != nil {
fmt.Println(err)
}
fmt.Printf("isSet: %v, isValid: %v, value: %v\n", currentUser3.Views.isSet, currentUser3.Views.isValid, currentUser3.Views.Value)
}
// UnmarshalJSON is custom unmarshal
func (i *OptionalInt) UnmarshalJSON(bytes []byte) error {
i.isSet = true
if string(bytes) == "null" {
i.isValid = false
return nil
}
var value int
if err := json.Unmarshal(bytes, &value); err != nil {
return err
}
i.isValid = true
i.Value = value
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment