go语言学习心得2

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值