這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
在讀kubernetes源碼的時候,讀到https://github.com/kubernetes/kubernetes/blob/master/pkg/apis/extensions/types.go k8s的type的時候,遇到這樣一段代碼,
// represents a scaling request for a resource.type Scale struct {unversioned.TypeMeta `json:",inline"`// Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata.api.ObjectMeta `json:"metadata,omitempty"`// defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status.Spec ScaleSpec `json:"spec,omitempty"`// current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only.Status ScaleStatus `json:"status,omitempty"`}
然後後面的 `` 裡面的 json字串,我就不明白了
這是Go語言的structTag
1 幹什麼用的?
如果希望手動設定結構體的成員和JSON欄位的對應關係,可以在定義結構體的時候給成員打標籤:
使用omitempty熟悉,如果該欄位為nil或0值(數字0,字串"",空數組[]等),則打包的JSON結果不會有這個欄位。
2 怎麼用啊 ? http://blog.csdn.net/tiaotiaoyly/article/details/38942311點擊開啟連結
type Message struct {Name string `json:"msg_name"` // 對應JSON的msg_nameBody string `json:"body,omitempty"` // 如果為空白置則忽略欄位Time int64 `json:"-"` // 直接忽略欄位}var m = Message{Name: "Alice",Body: "",Time: 1294706395881547000,}data, err := json.Marshal(m)if err != nil {fmt.Printf(err.Error())return}fmt.Println(string(data))Output:{"msg_name":"Alice"}