go語言學習心得2

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.