Go json Unmarshaller is not called

不羁岁月 提交于 2020-11-29 10:37:45

问题


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 Marshaller and Unmarshaller interfaces.

Here is my struct with implemented interfaces (I have also implemented Stringer):

type Data struct {
    Foo string `json:"foo"`
    bar string
}

func (d Data) MarshalJSON() ([]byte, error) {
    return []byte("{\"foo\":\"test\",\"bar\":\"data\"}"), nil
}

func (d Data) String() string {
    return fmt.Sprintf("Foo: %s, bar: %s", d.Foo, d.bar)
}

func (d Data) UnmarshalJSON(b []byte) error {
    d.bar = "testtest"
    d.Foo = "data"
    return nil
}

For Marshaller everything works as expected:

data := &Data{}
marshal, _ := json.Marshal(data)
fmt.Println(string(marshal))

The output as expected:

{"foo":"test","bar":"data"}

But Unmarshaller doesn't work as I was expecting:

jsonData := "{\"foo\":\"test\"}"
data := Data{}
json.Unmarshal([]byte(jsonData), data)
fmt.Println(data)

This code prints:

Foo: , bar:

Is there something that I'm missing here?


回答1:


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




回答2:


Data methods has value receiver, but the variable data has pointer type (*Data).

Pointer type variables cannot use functions with value receiver. Either change variable type or receiver type.

Also see https://github.com/golang/go/wiki/CodeReviewComments#receiver-type about receivers.



来源:https://stackoverflow.com/questions/46448102/go-json-unmarshaller-is-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!