JSON

JSON is quickly becoming the ubiquitous serialization format for web APIs, soit may be the most relevant when learning how to build web appsusing Go. Fortunately, Go makes it simple to work with JSON — it isextremely easy to turn existing Go structs into JSON using the encoding/jsonpackage from the standard library.

  1. package main
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. type Book struct {
  7. Title string `json:"title"`
  8. Author string `json:"author"`
  9. }
  10. func main() {
  11. http.HandleFunc("/", ShowBooks)
  12. http.ListenAndServe(":8080", nil)
  13. }
  14. func ShowBooks(w http.ResponseWriter, r *http.Request) {
  15. book := Book{"Building Web Apps with Go", "Jeremy Saenz"}
  16. js, err := json.Marshal(book)
  17. if err != nil {
  18. http.Error(w, err.Error(), http.StatusInternalServerError)
  19. return
  20. }
  21. w.Header().Set("Content-Type", "application/json")
  22. w.Write(js)
  23. }

Exercises

  • Read through the JSON API docs and find out how to rename and ignore fields for JSON serialization.
  • Instead of using the json.Marshal method, try using the json.Encoder API.
  • Figure our how to pretty print JSON with the encoding/json package.

原文: https://codegangsta.gitbooks.io/building-web-apps-with-go/content/rendering/json/index.html