Dou*_*sek 112 json marshalling 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[:]))
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
[ `go test -test.run="^TestCreateSingleItemResponse$"` | done: 2.195666095s ]
{TestObject f73h5jf8 Yuri Gagarin Yuri.Gagarin@Vostok.com}
{}
PASS
Run Code Online (Sandbox Code Playgroud)
为什么JSON基本上是空的?
Cer*_*món 201
您需要通过大写字段名称中的第一个字母来导出 TestObject中的字段.更改kind
对Kind
等.
type TestObject struct {
Kind string `json:"kind"`
Id string `json:"id,omitempty"`
Name string `json:"name"`
Email string `json:"email"`
}
Run Code Online (Sandbox Code Playgroud)
encoding/json包和类似的包忽略未导出的字段.
`json:"..."`
字段声明后面的字符串是struct标记.此结构中的标记在编组JSON时和从JSON编组时设置结构字段的名称.
Sou*_*gat 25
例子
var aName // private
var BigBro // public (exported)
var 123abc // illegal
func (p *Person) SetEmail(email string) { // public because SetEmail() function starts with upper case
p.email = email
}
func (p Person) email() string { // private because email() function starts with lower case
return p.email
}
Run Code Online (Sandbox Code Playgroud)
在 golang
在 struct 中的第一个字母必须大写,例如。电话号码 -> 电话号码
====== 添加细节
首先,我尝试这样编码
type Questions struct {
id string
questionDesc string
questionID string
ans string
choices struct {
choice1 string
choice2 string
choice3 string
choice4 string
}
}
Run Code Online (Sandbox Code Playgroud)
golang compile 不是错误并且不显示警告。但响应是空的,因为某事
之后,我搜索谷歌找到了这篇文章
结构类型和结构类型文字 文章然后...我尝试编辑代码。
//Questions map field name like database
type Questions struct {
ID string
QuestionDesc string
QuestionID string
Ans string
Choices struct {
Choice1 string
Choice2 string
Choice3 string
Choice4 string
}
}
Run Code Online (Sandbox Code Playgroud)
是工作。
希望得到帮助。
归档时间: |
|
查看次数: |
29853 次 |
最近记录: |