go struct转map

第一种方式:

使用json包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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进行解析

1
2
3
4
5
6
7
8
9
10
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
}
posted @   今天滴天气不错  阅读(516)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示