Go json Unmarshaller is not called

前端 未结 2 881
生来不讨喜
生来不讨喜 2021-01-23 18:14

I\'m fairly new to Golang. And I was looking for a way to do some custom stuff for marshaling and unmarshalling json. I have found the solution to implement M

2条回答
  •  粉色の甜心
    2021-01-23 18:44

    You have a few distinct problems here.

    • The method receiver must be a pointer if you want to modify the receiver, otherwise you're only modifying the copy local to the method.

    • You always need to unmarshal into a pointer.

    • You're declaring a "field" json tag for the Foo field, but passing in "foo"

    • You're calling json.Unmarshal inside your UnmarshalJSON method, which is going to recurse indefinitely.

    A working example would look like

    func (d *Data) UnmarshalJSON(b []byte) error {
        type data Data
        tmp := &data{bar: "bar"}
        err := json.Unmarshal(b, tmp)
        if err != nil {
            return err
        }
        *d = Data(*tmp)
        return nil
    }
    
    func main() {
        jsonData := "{\"field\":\"test\"}"
        data := Data{}
        json.Unmarshal([]byte(jsonData), &data)
        fmt.Printf("%#v\n", data)
    }
    

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

提交回复
热议问题