我们可以利用结构体,map都可以转json的特性来实现
func StructToMap(input interface{}, output interface{}) {
str, err := json.Marshal(input)
if err != nil {
fmt.Println("json.Marshal err", err)
return
}
_ = json.Unmarshal([]byte(str),&output)
}
type User struct {
Name string
Age int
}
func main() {
user := User{
Name:"胖大叔",
Age:18,
}
var UserMap map[string]interface{}
//结构体转map
StructToMap(user, &UserMap)
fmt.Println(UserMap)
//map转struct
StructToMap(UserMap, &user)
fmt.Println(user)
}