JSON unmarshal integer field into a string

后端 未结 2 550
渐次进展
渐次进展 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:47

    You can customize how the data structure is unamrshaled by implementing the json.Unamrshaler interface.

    The simplest way to handle unknown types is to nnmarshal the JSON into an intermediate structure, and handle the type assertions and validation during deserialization:

    type test struct {
        Foo string `json:"foo"`
    }
    
    func (t *test) UnmarshalJSON(d []byte) error {
        tmp := struct {
            Foo interface{} `json:"foo"`
        }{}
    
        if err := json.Unmarshal(d, &tmp); err != nil {
            return err
        }
    
        switch v := tmp.Foo.(type) {
        case float64:
            t.Foo = strconv.Itoa(int(v))
        case string:
            t.Foo = v
        default:
            return fmt.Errorf("invalid value for Foo: %v", v)
        }
    
        return nil
    }
    

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

提交回复
热议问题