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 = "[email protected]"
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 [email protected]}
{}
PASS
JSON が本質的に空なのはなぜですか?
ベストアンサー1
必要がある輸出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:"..."`
フィールド宣言に続く文字列は構造体タグこの構造体のタグは、JSON との間でマーシャリングするときに構造体のフィールドの名前を設定します。