這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Unmarshal json 2 custom define object
心得總結
according to test case, we reached the following conclusions:no mater what format of source json field value, (It may be a variety of situations as follows) 1. Initials: 'Devicetype' 2. ALL CAPS: 'DEVICETYPE' 3. All lowercase: 'devicetype' 4. Capitalize the first letter of each word: 'DeviceType'Unmarshal json to object, the define of object 's json part can only be defined as: `json:"devicetype"`#中文簡要總結1. 首字母大寫2. 全部大寫3. 全部小寫4. 每單字首大寫5. ...映射到自訂的結構體上時,json部分的寫法只需要寫成 `json:"全部小寫"` 即可eg:`json:devicetype`
測試case
func Test_UT_MarshalAndUnmarshal(t *testing.T) { jsonData := `{"ASW-2C-03.SQA.TBC":{"Attributes":{"Devicetype":"network_device","ExpectedLink":"expectedLinkValue","Hostname":"ASW-2C-03.SQA.TBC","ID":"ASW-2C-03.SQA.TBC","Ip":"10.104.46.8","manufacturer":"h3c","Model":"WS-C3560G-24TS","Sn":"bbd20dfd-5260-45f0-936a-5b13c4c571c0","uplinkinfo":"uplink_info"}}}` type APIServer2TempItem struct { Id string `json:"id"` Ip string `json:"ip"` Model string `json:"model"` Sn string `json:"sn"` Manufacturer string `json:"manufacturer"` UplinkInfo string `json:"uplinkinfo"` ExpectedLink string `json:"expectedlink` DeviceType string `json:"devicetype"` } var m map[string]map[string]*APIServer2TempItem = make(map[string]map[string]*APIServer2TempItem) bytes := []byte(jsonData) json.Unmarshal(bytes, &m) expected, ok := m["ASW-2C-03.SQA.TBC"]["Attributes"] assert.Equal(t, ok, true) expectedValue := "network_device" assert.Equal(t, expected.DeviceType, expectedValue) expectedValue = "expectedLinkValue" assert.Equal(t, expected.ExpectedLink, expectedValue) expectedValue = "ASW-2C-03.SQA.TBC" assert.Equal(t, expected.Id, expectedValue) expectedValue = "10.104.46.8" assert.Equal(t, expected.Ip, expectedValue) expectedValue = "h3c" assert.Equal(t, expected.Manufacturer, expectedValue) expectedValue = "WS-C3560G-24TS" assert.Equal(t, expected.Model, expectedValue) expectedValue = "bbd20dfd-5260-45f0-936a-5b13c4c571c0" assert.Equal(t, expected.Sn, expectedValue) expectedValue = "uplink_info" assert.Equal(t, expected.UplinkInfo, expectedValue)}