1. 程式人生 > 其它 >golang型別轉換

golang型別轉換

結構體轉json
	type User struct {
		UserName string  `json:"user_name"`
		Sex      string  `json:"sex"`
		Score    float32 `json:"score"`
		Age      int32   `json:"age"`
	}
	user := &User{
		UserName: "users1",
		Sex:      "男",
		Score:    99.2,
		Age:      18,
	}
	data, _ := json.Marshal(user)
	fmt.Printf("json str:%s\n", string(data))

json轉map
	str := `{"user_name":"users1","sex":"男","score":99.2,"age":18}`
	var m map[string]interface{}
	//轉json
	json.Unmarshal([]byte(str), &m)
map轉結構體
package main

import (
	"encoding/json"
	"fmt"
	"github.com/mitchellh/mapstructure"
)
type User struct {
	UserName string  `json:"user_name"`
	Sex      string  `json:"sex"`
	Score    float32 `json:"score"`
	Age      int32   `json:"age"`
}

func main() {
	//map轉struct
	str := `{"user_name":"users1","sex":"男","score":99.2,"age":18}`
	var m map[string]interface{}
	json.Unmarshal([]byte(str), &m)
	structs := User{}
	mapstructure.Decode(m, &structs)
	fmt.Println(structs.Age)
}
map轉字串
m := map[string]string{"type": "10", "msg": "hello."}
	mJson, _ := json.Marshal(m)
	mString := string(mJson)
	fmt.Printf("print mString:%s", mString)