package mainimport("fmt""github.com/goinggo/mapstructure")typePerson struct { Name string Ageint} func MapToStruct() { mapInstance := make(map[string]interface{}) mapInstance["Name"] ="liang637210"mapInstance["Age"] =28var person Person //将map转换为指定的结构体iferr := mapstructure.Dec...
v:=map[string]string{"time":"2019-07-02"}typeResultstruct{Timetime.Time`json:"time"`} 首先...
b, _ := json.Marshal(map[string]int{"test":1,"try":2}) fmt.Println(string(b)) } map转struct 需要安装一个第三方库 在命令行中运行: go get github.com/goinggo/mapstructure 例子: func MapToStructDemo(){ mapInstance := make(map[string]interface{}) mapInstance["Name"] ="jqw"mapInsta...
func TestMapToStructByJson(t *testing.T) { beforeMap := map[string]interface {}{ "id":"123", "user_name":"酒窝猪", "address":[]map[string]interface{}{{"address": "address01"}, {"address": "address02"}}, } var afterStruct =UserInfoVo{} before := time.Now() marshal, err ...
beforeMap := map[string]interface {}{ "id":"123", "user_name":"酒窝猪", "address":[]map[string]interface{}{{"address": "address01"}, {"address": "address02"}}, } var afterStruct =UserInfoVo{} before := time.Now() marshal, err := json.Marshal(beforeMap) if err!=nil{ fmt...
2. 合并 map 到 struct 接下来我们看另一个场景:我们有一个 map,需要将其内容合并到一个已有的 struct 中。这种需求在动态配置加载时特别常见。 funcmapToStruct(){ varm =make(map[string]interface{})m["name"] ="Tom"m["age"] =23m["email"] ="12...
StructToJsonDemo()} 输出:⼆、json和map互转 (1)json转map例⼦:func JsonToMapDemo() { jsonStr := `{"name": "jqw","age": 18}`var mapResult map[string]interface{} err := json.Unmarshal([]byte(jsonStr), &mapResult)if err != nil { fmt.Println("JsonToMapDemo err: ", err)...
$ go get github.com/goinggo/mapstructure 之后我们就可以直接使用它提供的方法将 map 转换为 struct,让我们直接上代码吧 package commontest import ( "testing" "github.com/goinggo/mapstructure" ) func TestMap2Struct(t *testing.T) { mapInstance := make(map[string]interface{}) ...
注意json里面的key和struct里面的key要一致,struct中的key的首字母必须大写,而json中大小写都可以。 package main import ("fmt""encoding/json") type Peoplestruct{ Namestring`json:"name_title"` Ageint`json:"age_size"` } func JsonToStructDemo(){ ...
一、map与struct互转 实现map到struct的转换有两途径:一是借助第三方包github.com/mitchellh/mapstructure,二是将map转换为json,再由json转换为struct,操作繁琐。通过第三方库mapstructure进行转换更为高效,所需时间仅为61.757μs,优于通过json转换的方式,时间约为134.299μs。另一种转换方式是利用...