How can I implement UnmarshalJSON for a type derived from a scalar in Go?

前端 未结 2 1822
执笔经年
执笔经年 2021-01-15 04:25

I have a simple type that implements conversion of subtyped integer consts to strings and vice versa in Go. I want to be able to automatically unmarshal strings in JSON to v

2条回答
  •  庸人自扰
    2021-01-15 04:48

    Use a pointer receiver for the unmarshal method. If a value receiver is used, changes to the receiver are lost when the method returns.

    The argument to the unmarshal method is JSON text. Unmarshal the JSON text to get a plain string with all JSON quoting removed.

    func (intValue *PersonID) UnmarshalJSON(data []byte) error {
      var s string
      if err := json.Unmarshal(data, &s); err != nil {
        return err
      }
      *intValue = Lookup(s)
      return nil
    }
    

    There's a mismatch between the JSON tags an the example JSON. I changed the JSON to match the tag, but you can change it the other way.

    if err := json.Unmarshal([]byte(`{"person": "Ralph", "count": 4, "greeting": "Hello"}`), &m); err != nil {
    

    playground example

提交回复
热议问题