Skip to content

Instantly share code, notes, and snippets.

@meblum
Last active February 2, 2021 03:13
Show Gist options
  • Select an option

  • Save meblum/ed07509595ef2d2cfb542f818c3b3917 to your computer and use it in GitHub Desktop.

Select an option

Save meblum/ed07509595ef2d2cfb542f818c3b3917 to your computer and use it in GitHub Desktop.
Implementation of a custom https://golang.org/pkg/encoding/json/#Unmarshaler to convert a JSON int value to a GO bool value. Returns a formed https://golang.org/pkg/encoding/json/#UnmarshalTypeError when failed. https://play.golang.org/p/oe_JPzDFvke
package main
import (
"encoding/json"
"fmt"
)
type myBool bool
func (b *myBool) UnmarshalJSON(v []byte) error {
switch string(v) {
case "0":
*b = false
return nil
case "1":
*b = true
return nil
default:
//return a *json.UnmarshalTypeError
//see also https://github.com/golang/go/issues/11858
var newB bool
return json.Unmarshal(v, &newB)
}
}
type T struct {
A myBool
}
func main() {
t := T{}
e := json.Unmarshal([]byte(`{"a":1}`), &t)
if e != nil {
fmt.Printf("%#+v", e)
} else {
fmt.Printf("%+v", t)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment