[go-每日一库] golang中借助json等库实现struct和map互转
1.struct -> map1.1 version-1
指定struct中tag-map
// version-1, struct -> map
type User struct {
Name string `map:"name,omitempty"`
Age int `map:"age,omitempty"`
Profile UserProfile `map:"profile,dive"` // struct dive
NoDive StructDive `map:"no_dive, omitempty"` // no dive
}
type UserProfile struct {
Address string `map:"address"`
City string `map:"city"`
Job string `map:"job"`
}
type StructDive struct {
NoDive int
}
func newUser() User {
name := "spiderMan"
age := 12
profile := UserProfile{
Address: "Jiaozi Road",
City: "chengdu",
Job: "Backend Engineer",
}
nodive := StructDive{20}
return User{
Name: name,
Age: age,
Profile: profile,
NoDive: nodive,
}
}
func struct2map(v interface{}) mapinterface{} {
data, _ := json.Marshal(v)
m := make(mapinterface{})
_ = json.Unmarshal(data, &m)
return m
}1.2 version-2
不指定struct直接转map
// version-2 struct -> map
type User2 struct {
Name string `json:"name"`
Profile UserProfile `json:"profile"`
}
type UserProfile2 struct {
Address string `json:"address"`
City string `json:"city"`
Job string `json:"job"`
}
func newUser2() User2 {
return User2{
Name: "superMan",
Profile: UserProfile{
Address: "Tiananmen",
City: "beijing",
Job: "HR",
},
}
}2.map -> struct
func newMap() mapinterface{} {
m := make(mapinterface{})
m["name"] = "super-man"
m["profile"] = mapinterface{}{
"address": "Tiananmen",
"city": "beijing",
"job": "HR",
}
return m
}
// map -> struct, dst should be ptr
func map2Struct(m mapinterface{}, dst interface{}){
data, err := json.Marshal(m)
if err != nil {
fmt.Println(err)
}
_ = json.Unmarshal(data, &dst)
}以下是测试情况:
func main(){
// 1.struct -> map
// version-1
user := newUser()
m := struct2map(user)
for k,v := range m {
fmt.Printf("key: %s, val: %v\n", k, v)
switch reflect.TypeOf(v).Kind() {
case reflect.Map:
for k2, v2 := range v.(mapinterface{}) {
fmt.Printf("key-2: %s, val-2: %v\n", k2, v2)
}
}
}
/*
key: Age, val: 12
key: Profile, val: map
key-2: Address, val-2: Jiaozi Road
key-2: City, val-2: chengdu
key-2: Job, val-2: Backend Engineer
key: NoDive, val: map
key-2: NoDive, val-2: 20
key: Name, val: spiderMan
*/
// version-2
fmt.Println("\nit's version-2 struct to map")
user2 := newUser2()
m2 := struct2map(user2)
for k,v := range m2 {
fmt.Printf("key: %s, val: %v\n", k, v)
switch reflect.TypeOf(v).Kind() {
case reflect.Map:
for k2, v2 := range v.(mapinterface{}) {
fmt.Printf("key-2: %s, val-2: %v\n", k2, v2)
}
}
}
/*
key: name, val: superMan
key: profile, val: map
key-2: Job, val-2: HR
key-2: Address, val-2: Tiananmen
key-2: City, val-2: beijing
*/
// 2.map -> struct
fmt.Println("\nmap -> json")
m3 := newMap()
var user3 User2
map2Struct(m3, &user3)
fmt.Println(user3)
/*
{super-man {Tiananmen beijing HR}}
*/
}
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]