[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 2022-06-24 16:00  进击的davis  阅读(242)  评论(0编辑  收藏  举报

导航