go语言学习心得2

lingyun1981 · · 938 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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)
}


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:lingyun1981

查看原文:go语言学习心得2

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:701969077

938 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传