json.go 796 B

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