[go-每日一库] golang借助json库实现struct/map与json的互转

话不多说,直接上代码。

1.功能函数

// json -> struct/map, dst should be ptr
func Json2StructOrMap(raw string, dst interface{}) {
_ = json.Unmarshal([]byte(raw), &dst)
}
// struct/map -> json
func StructOrMap2Json(src interface{}) string {
data, _ := json.Marshal(src)
return string(data)
}

2.测试代码

// usage struct
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Gender string `json:"gender"`
}
func main() {
// json -> unmarshal
raw := `{"one": 2}`
var dst map[string]int
_ = json.Unmarshal([]byte(raw), &dst)
fmt.Printf("after unmarshal, dst data: %v, type: %T\n", dst, dst)
// marshal -> json
src := map[string]string{"one": "one"}
dstByte, _ := json.Marshal(src)
srcJson := string(dstByte)
fmt.Printf("src->json: %v, type: %T\n", srcJson, srcJson)
// struct -> json
user := User{"Bob", 25, "male"}
userWithJson := StructOrMap2Json(user)
fmt.Printf("struct -> json, type: %T, val: %v\n", userWithJson, userWithJson)
// struct -> json, type: string, val: {"name":"Bob","age":25,"gender":"male"}
// map -> json
usermap := map[string]interface{}{"name": "Bob", "age": 25, "gender": "male"}
usermapWithJson := StructOrMap2Json(usermap)
fmt.Printf("map -> json, type: %T, val: %v\n", usermapWithJson, usermapWithJson)
//map -> json, type: string, val: {"age":25,"gender":"male","name":"Bob"}
// json -> struct/map
rawUser := `{"name":"Bob","age":25,"gender":"male"}`
var m map[string]interface{}
Json2StructOrMap(rawUser, &m)
var user_1 User
Json2StructOrMap(rawUser, &user_1)
fmt.Printf("json -> map, type: %T, val: %v\n", m, m)
fmt.Printf("json -> struct, type: %T, val: %v\n", user_1, user_1)
/*
json -> map, type: map[string]interface {}, val: map[age:25 gender:male name:Bob]
json -> struct, type: main.User, val: {Bob 25 male}
*/
}

posted on   进击的davis  阅读(276)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示