json标签

  1. type UserInfo struct {
  2. Name string `json:"name"`
  3. Email string `json:"email"`
  4. Password string `json:"password"`
  5. }

结构体到JSON

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

JSON到结构体

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

示例代码

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type UserInfo struct {
  7. Name string `json:"name"`
  8. Email string `json:"email"`
  9. Password string `json:"password"`
  10. }
  11. func main() {
  12. user1 := UserInfo{
  13. Name: "luckFang",
  14. Email: "1318659507@qq.com",
  15. Password: "123456",
  16. }
  17. // 生成json
  18. marshal, _ := json.Marshal(&user1)
  19. rawJson := fmt.Sprintf("%s", marshal)
  20. fmt.Println(rawJson)
  21. var user2 UserInfo
  22. // 解析json到结构体
  23. _ = json.Unmarshal([]byte(rawJson), &user2)
  24. fmt.Printf("%#v\n", user2)
  25. }
  1. {"name":"luckFang","email":"1318659507@qq.com","password":"123456"}
  2. main.UserInfo{Name:"luckFang", Email:"1318659507@qq.com", Password:"123456"}