Golang 中的继承和 Json

Ale*_*iak 4 json go

有两个结构体A和B。B包含A。还有一个附加到A的函数。它返回父对象的json。当我在 B 的实例上调用函数时,我希望看到 json 中的所有对象字段,但我只得到 A 的字段。请看代码:

type A struct {
    Foo string
}

type B struct {
    A
    Bar string
}

func (object *A) toJson() []byte {
    res, _ := json.Marshal(&object)
    return res
}


func main() {
    b := B{}
    fmt.Println(string(b.toJson()))
}
Run Code Online (Sandbox Code Playgroud)

我期望得到{"Foo":"", "Bar":""}但结果是{"Foo":""}。第一种方法是为这两个结构定义两个单独的函数。但有没有第二种解决方案只有一种功能呢?先感谢您。

Guj*_*ana 5

您的方法 toJson() 来自 A 结构。将其更改为 struct B 然后您将得到预期的结果。

package main

import (
    "encoding/json"
    "fmt"
)

type A struct {
    Foo string `json:"foo"`
}

type B struct {
    A
    Bar string `json:"bar"`
}

func (object *B) toJson() []byte {
    res, _ := json.Marshal(&object)
    return res
}

func main() {
    c := B{}
    fmt.Println(string(c.toJson()))
}
Run Code Online (Sandbox Code Playgroud)