结构体转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)