json.Marshal(struct) 返回“{}"; [英] json.Marshal(struct) returns "{}"

查看:36
本文介绍了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天全站免登陆