基本情况
// 定义结构体的时候,只有字段名是大写的,才会被编码到json当中
// 因此,json中并没有password字段
type Account struct {
Email string
password string
Money float64
}
func main() {
account := Account{
Email: "rsj217@gmail.com",
password: "123456",
Money: 100.5,
}
rs, err := json.Marshal(account)
if err != nil{
log.Fatalln(err)
}
fmt.Println(rs)
fmt.Println(string(rs))
}
输出:
[123 34 69 109 97 105 108 34 58 34 114 115 106 50 49 55 64 103 109 97 105 108 46 99 111 109 34 44 34 77 111 110 101 121 34 58 49 48 48 46 53 125]
{"Email":"rsj217@gmail.com","Money":100.5}
JSON字段重命名
type Account struct {
Email string `json:"email"`
Password string `json:"pass_word"`
Money float64 `json:"money"`
}
func main() {
account := Account{
Email: "rsj217@gmail.com",
Password: "123456",
Money: 100.5,
}
rs, err := json.Marshal(account)
...
}
输出:
{"email":"rsj217@gmail.com","pass_word":"123456","money":100.5}
更多功能
-
type Account struct {
Email string `json:"email"`
Password string `json:"password,omitempty"`
Money float64 `json:"-"`
}
输出
{"email":"rsj217@gmail.com","money":100.5}
omitempty
type Account struct {
Email string `json:"email"`
Password string `json:"password,omitempty"`
Money float64 `json:"money"`
}
func main() {
account := Account{
Email: "rsj217@gmail.com",
Password: "",
Money: 100.5,
}
...
}
输出
{"email":"rsj217@gmail.com","money":100.5}
string
type Account struct {
Email string `json:"email"`
Password string `json:"password,omitempty"`
Money float64 `json:"money,string"`
}
func main() {
account := Account{
Email: "rsj217@gmail.com",
Password: "123",
Money: 100.50,
}
...
}
输出
{"email":"rsj217@gmail.com","money":"100.5"}