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)
}
有疑问加站长微信联系(非本文作者)