当前位置:网站首页>Go learning --- structure to map[string]interface{}

Go learning --- structure to map[string]interface{}

2022-07-06 00:15:00 Duck boss

One 、 The structure turns map[string]interface{} The type of question

package main

import (
	"encoding/json"
	"fmt"
)

// Define a structure 
type User struct {
	Name string `json:"name"`
	Age int `json:"age"`
}
func main() {
	user := User{
		Name: " Xiao Wang ",
		Age:  25,
	}
	m, _ := json.Marshal(&user)
	var ma map[string]interface{}
	json.Unmarshal(m,&ma)
	for s, i := range ma {
		fmt.Printf("s=%v i=%v i Of type:%T\n",s,i,i)
	}
}

  resolvent :

package main

import (
	"fmt"
	"reflect"
)
// Define a structure 
type User struct {
	Name string `json:"name"`
	Age int `json:"age"`
}

func ToMap(in interface{},tagName string)(map[string]interface{},error)  {
	myMap := make(map[string]interface{})
	v := reflect.ValueOf(in)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	if v.Kind() != reflect.Struct {
		return nil,fmt.Errorf(" Type error ",v)
	}
	t := v.Type()
	// Traverse structure fields 
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		get := field.Tag.Get(tagName)
		if get != "" {
			myMap[get] = v.Field(i).Interface()
		}
	}
	return myMap,nil
}
func main() {
	user := User{
		Name: " Xiao Wang ",
		Age:  25,
	}
	toMap, _ := ToMap(&user, "json")
	for s, i := range toMap {
		fmt.Printf("s=%v i=%v i Of type:%T\n",s,i,i)
	}
}

 

原网站

版权声明
本文为[Duck boss]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140235517133.html