当前位置:网站首页>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)
}
}
边栏推荐
- Cloudcompare & PCL point cloud randomly adds noise
- Qt QPushButton详解
- Open source CRM customer relationship system management system source code, free sharing
- 单商户V4.4,初心未变,实力依旧!
- AtCoder Beginner Contest 258【比赛记录】
- Key structure of ffmpeg - avformatcontext
- N1 # if you work on a metauniverse product [metauniverse · interdisciplinary] Season 2 S2
- 数据库遇到的问题
- 【GYM 102832H】【模板】Combination Lock(二分图博弈)
- Ffmpeg learning - core module
猜你喜欢
随机推荐
Upgrade openssl-1.1.1p for openssl-1.0.2k
FFMPEG关键结构体——AVFormatContext
Transport layer protocol ----- UDP protocol
Doppler effect (Doppler shift)
MySQL之函数
"14th five year plan": emphasis on the promotion of electronic contracts, electronic signatures and other applications
FFT 学习笔记(自认为详细)
MySQL global lock and table lock
openssl-1.0.2k版本升级openssl-1.1.1p
AtCoder Beginner Contest 254【VP记录】
多普勒效應(多普勒頻移)
Open source CRM customer relationship system management system source code, free sharing
【DesignMode】装饰者模式(Decorator pattern)
第16章 OAuth2AuthorizationRequestRedirectWebFilter源码解析
【GYM 102832H】【模板】Combination Lock(二分图博弈)
Shardingsphere source code analysis
单商户V4.4,初心未变,实力依旧!
跟着CTF-wiki学pwn——ret2libc1
2022.7.5-----leetcode. seven hundred and twenty-nine
Priority queue (heap)