Last active
February 2, 2021 03:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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