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.

Revisions

  1. meblum revised this gist Feb 2, 2021. No changes.
  2. meblum revised this gist Feb 2, 2021. No changes.
  3. meblum created this gist Feb 2, 2021.
    45 changes: 45 additions & 0 deletions unmarshaler.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    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)
    }

    }