JSON unmarshal integer field into a string

后端 未结 2 545
渐次进展
渐次进展 2021-02-06 10:27

I am struggling with deserializing a integer into a string struct field. The struct field is a string and is expected to be assignable from users of my library. That\'s why I wa

2条回答
  •  情书的邮戳
    2021-02-06 10:48

    To handle big structs you can use embedding.

    Updated to not discard possibly previously set field values.

    func (t *T) UnmarshalJSON(d []byte) error {
        type T2 T // create new type with same structure as T but without its method set!
        x := struct{
            T2 // embed
            Foo json.Number `json:"foo"`
        }{T2: T2(*t)} // don't forget this, if you do and 't' already has some fields set you would lose them
    
        if err := json.Unmarshal(d, &x); err != nil {
            return err
        }
        *t = T(x.T2)
        t.Foo = x.Foo.String()
        return nil
    }
    

    https://play.golang.org/p/BytXCeHMvt

提交回复
热议问题