duanpan3166 2017-09-27 12:38
浏览 70
已采纳

Go json Unmarshaller没有被调用

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?

  • 写回答

2条回答 默认 最新

  • duanfan5012 2017-09-27 12:45
    关注

    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
    ", data)
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题