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基本上是空的?
我正在使用这个库来访问couchDB(cloudant是具体的)"github.com/mikebell-org/go-couchdb",我注意到了一个问题.
当我将数据添加到数据库并传入结构时,只添加以大写字母开头的结构字段.
例如
type Person struct {
name string
Age int
}
func main() {
db, _ := couchdb.Database(host, database, username, password)
joe := Person{
name: "mike",
Age: 190,
}
m, _ := db.PostDocument(joe)
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,只有"age"字段已更新并插入到我的数据库中.
我在另一个案例中也注意到了这个问题 - 当我做这样的事情时:
type Sample struct {
Name string
age int
}
joe := Sample{
Name: "xx",
age: 23,
}
byt, _ := json.Marshal(joe)
post_data := strings.NewReader(string(byt))
fmt.Println(post_data)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,只会打印出名称:
output : &{{"Name":"xx"} 0 -1}
Run Code Online (Sandbox Code Playgroud)
为什么是这样?如果我想要一个小写的字段并且在数据库中,那可能吗?