小编典典

json.Marshal(struct)返回“ {}”

go

type TestObject struct {
    kind string `json:"kind"`
    id   string `json:"id, omitempty"`
    name  string `json:"name"`
    email string `json:"email"`
}

func TestCreateSingleItemResponse(t *testing.T) {
    testObject := new(TestObject)
    testObject.kind = "TestObject"
    testObject.id = "f73h5jf8"
    testObject.name = "Yuri Gagarin"
    testObject.email = "Yuri.Gagarin@Vostok.com"

    fmt.Println(testObject)

    b, err := json.Marshal(testObject)

    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(string(b[:]))
}

这是输出:

[ `go test -test.run="^TestCreateSingleItemResponse$"` | done: 2.195666095s ]
    {TestObject f73h5jf8 Yuri Gagarin Yuri.Gagarin@Vostok.com}
    {}
    PASS

为什么JSON本质上是空的?


阅读 371

收藏
2020-07-02

共1个答案

小编典典

您需要通过大写字段名称中的第一个字母来导出
TestObject中的字段。更改kindKind,依此类推。

type TestObject struct {
 Kind string `json:"kind"`
 Id   string `json:"id,omitempty"`
 Name  string `json:"name"`
 Email string `json:"email"`
}

encoding / json包和类似的包会忽略未导出的字段。

json:"..."字段声明之后的字符串是struct标签。在与JSON封送时,此struct中的标记设置该结构的字段名称。

[playground](https://play.golang.org/p/n19J5XhiGIL)

2020-07-02