首页 > 编程语言 > golang 实现json类型不确定时的转换
2021
01-26

golang 实现json类型不确定时的转换

将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”}}

补充:gin bindJSON结构体中有不确定类型的字段

结构体中有不确定类型的字段,用interface{},BindJSON后根据输入自动存储对应类型,比如

type student struct {
 Name string   `json:"name"`
 Info interface{} `json:"info"`
}

比如,info的输入

输入

类型

12

float64

“str”

string

{"str":"value"}

map[string]interface {}

true

bool

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自学编程网。如有错误或未考虑完全的地方,望不吝赐教。

编程技巧