LoginSignup
5
4

More than 5 years have passed since last update.

stringerで作った型の値をJSONにするときに文字列にする

Posted at

すごい局所的だけど stringerで型を作って、それを構造体に入れたい場合の話。

//go:generate stringer -type=City
type City int

const (
    Tokyo City = iota
    Osak
    NewYork
)

type Address struct {
    City City `json:"city"`
}

func main() {
    a := Address{NewYork}
    bs, _ := json.Marshal(a)
    fmt.Println(string(bs)) // {"city":2}
}

最後の結果を{"city":"NewYork"}にしたいとき

//go:generate stringer -type=City
type City int

const (
    Tokyo City = iota
    Osaka
    NewYork
)

// Marshal時にstringで使った文字列を返す
func (c City) MarshalJSON() ([]byte, error) {
    return []byte(`"` + c.String() + `"`), nil
}

type Address struct {
    City City `json:"city"`
}

func main() {
    a := Address{NewYork}
    bs, _ := json.Marshal(a)
    fmt.Println(string(bs)) // {"city":"NewYork"}
}

func (c City) MarshalJSON() ([]byte, error) {
    return []byte(`"` + c.String() + `"`), nil
}

前後に"が必要。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4