go struct转map - 今天滴天气不错 - 博客园

go struct转map

第一种方式:

使用json包

package main

import (

"encoding/json"
"fmt"
"reflect"

)

func main() {

type User struct {
    Id   int64  \`json:"Id"\`
    Name string \`json:"Name"\`
    Sex  int    \`json:"Sex"\`
    Age  uint   \`json:"Age"\`
}
lisi := User{
    Id:   1008,
    Name: "lisi",
    Sex:  1,
    Age:  26,
}
userByte, err := json.Marshal(lisi)
if err != nil {
    panic("json encode错误=" + err.Error())
}
var userMap = make(map\[string\]interface{})
unmarshalErr := json.Unmarshal(userByte, &userMap)
if unmarshalErr != nil {
    panic("json decode错误=" + unmarshalErr.Error())
}
fmt.Printf("%+v", userMap)
//注意⚠️ 这里 Id本身应该是int64,通过json包转map 会变成float64,使用时应再次转换类型
//报错:panic: interface conversion: interface {} is float64, not int64
//fmt.Println(userMap\["Id"\].(int64))
//报错:panic: interface conversion: interface {} is float64, not uint
//fmt.Println(userMap\["Age"\].(uint))

//正确写法
fmt.Println(int64(userMap\["Id"\].(float64)))
fmt.Println(uint(userMap\["Age"\].(float64)))

fmt.Println(userMap\["Id"\], userMap\["Name"\])

}

第二种方式:

利用reflect进行解析

func structToMap(obj interface{}) map[string]interface{} {

//reflect
v := reflect.ValueOf(obj)
t := reflect.TypeOf(obj)
ret := make(map\[string\]interface{})
for i := 0; i < t.NumField(); i++ {
    ret\[t.Field(i).Name\] = v.Field(i).Interface()
}
return ret

}

分类: golang

好文要顶;) 关注我;) 收藏该文;) ; "分享至新浪微博") ; "分享至微信")

今天滴天气不错
粉丝 - 0 关注 - 0

+加关注;)

0

0

« 上一篇: git命令缩写配置

posted @ 2022-07-24 10:52  今天滴天气不错  阅读(64)  评论(0)  编辑  收藏举报)


原网址: 访问
创建于: 2022-09-06 19:19:35
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论