json.Marshal(struct)返回``{}'' [英] json.Marshal(struct) returns "{}"

查看:191
本文介绍了json.Marshal(struct)返回``{}''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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本质上是空的?

Why is the JSON essentially empty?

推荐答案

您需要导出通过大写字段名称中的第一个字母在TestObject中的字段.将kind更改为Kind,依此类推.

You need to export the fields in TestObject by capitalizing the first letter in the field name. Change kind to Kind and so on.

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

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

The encoding/json package and similar packages ignore unexported fields.

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

The `json:"..."` strings that follow the field declarations are struct tags. The tags in this struct set the names of the struct's fields when marshaling to and from JSON.

游乐场

这篇关于json.Marshal(struct)返回``{}''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆