go语言-JSON

luckyFang 2021年03月15日 95次浏览

json标签

type UserInfo struct {
	Name     string `json:"name"`
	Email    string `json:"email"`
	Password string `json:"password"`
} 

结构体到JSON

marshal, _ := json.Marshal(&user1)

JSON到结构体

_ = json.Unmarshal([]byte(rawJson), &user2)

示例代码

package main

import (
	"encoding/json"
	"fmt"
)

type UserInfo struct {
	Name     string `json:"name"`
	Email    string `json:"email"`
	Password string `json:"password"`
}

func main() {
	user1 := UserInfo{
		Name:     "luckFang",
		Email:    "1318659507@qq.com",
		Password: "123456",
	}

	// 生成json
	marshal, _ := json.Marshal(&user1)
	rawJson := fmt.Sprintf("%s", marshal)
	fmt.Println(rawJson)
	var user2 UserInfo

	// 解析json到结构体
	_ = json.Unmarshal([]byte(rawJson), &user2)
	fmt.Printf("%#v\n", user2)

}

{"name":"luckFang","email":"1318659507@qq.com","password":"123456"}
main.UserInfo{Name:"luckFang", Email:"1318659507@qq.com", Password:"123456"}