将json转为结构体时,经常会遇到无法确定某个字段类型的情况。在Go中可以使用interface 任意类型来解决。

// convert json to struct
// type uncertain

package main


import (
    "fmt"
    "encoding/json"
)

type Host struct {
    Id interface{}
    IdcId interface{}
}

func main() {

    b := []byte(`{"ID": 11, "IDCid": "1001"}`)

    m := Host{}

    err := json.Unmarshal(b, &m)
    if err != nil {

        fmt.Println("Umarshal failed:", err)
        return
    }


    fmt.Printf("m:%#v\n", m)
}

output:

m:main.Host{Id:11, IdcId:”1001”}}文章来源地址https://www.yii666.com/blog/37454.html文章地址https://www.yii666.com/blog/37454.html网址:yii666.com<网址:yii666.com文章来源地址:https://www.yii666.com/blog/37454.html