json

json序列化

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type Address struct {
  9. Type string
  10. City string
  11. Country string
  12. }
  13. type VCard struct {
  14. FirstName string
  15. LastName string
  16. Addresses []*Address
  17. Remark string
  18. }
  19. func main() {
  20. pa := &Address{"private", "Aartselaar", "Belgium"}
  21. wa := &Address{"work", "Boom", "Belgium"}
  22. vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"}
  23. js, _ := json.Marshal(vc)
  24. fmt.Printf("JSON format: %s", js)
  25. // 序列化到文件
  26. file, _ := os.OpenFile("vcard.json", os.O_CREATE|os.O_WRONLY, 0666)
  27. defer file.Close()
  28. enc := json.NewEncoder(file)
  29. err := enc.Encode(vc)
  30. if err != nil {
  31. log.Println("Error in encoding json")
  32. }
  33. }