markphelps / optional

Optional is a library of optional Go types
https://godoc.org/github.com/markphelps/optional
MIT License
209 stars 19 forks source link

JSON Marshal For Primitive Wrappers #1

Closed randyp closed 6 years ago

randyp commented 6 years ago

I would like your primitive wrappers, such as optional.Bool, to marshal and unmarshal to json accordingly. Right now they are marshaled as objects.

package main

import (
    "encoding/json"
    "github.com/markphelps/optional"
    "os"
)

type Foo struct {
    Bar optional.Bool `json:"bar"`
}

func main() {
    json.NewEncoder(os.Stdout).Encode(&Foo{Bar:optional.Bool{}}) // {}
    json.NewEncoder(os.Stdout).Encode(&Foo{Bar:optional.NewBool(true)}) // {"bar": true}
    json.NewEncoder(os.Stdout).Encode(&Foo{Bar:optional.NewBool(false)}) // {"bar":false}
}
lunemec commented 6 years ago

This could be added to the generator template and re-generated the primitive types.

markphelps commented 6 years ago

Thanks for the idea @randyp! Checkout the latest version and let me know if that fits your usecase.