gpt4 book ai didi

json.Marshal(struct) 返回 "{}"

转载 作者:IT王子 更新时间:2023-10-29 02:21:05 25 4
gpt4 key购买 nike

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

最佳答案

您需要export TestObject 中的字段,方法是将字段名称中的第一个字母大写。将 kind 更改为 Kind 等等。

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

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

字段声明后的 `json:"..."` 字符串是 struct tags .此结构中的标记在与 JSON 进行编码(marshal)处理时设置结构字段的名称。

Ru it on the playground .

关于json.Marshal(struct) 返回 "{}",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com