返回介绍

JSON

发布于 2025-02-25 22:26:26 字数 1270 浏览 0 评论 0 收藏 0

JSON is quickly becoming the ubiquitous serialization format for web APIs, so it may be the most relevant when learning how to build web apps using Go. Fortunately, Go makes it simple to work with JSON -- it is extremely easy to turn existing Go structs into JSON using the encoding/json package from the standard library.

package main

import (
  "encoding/json"
  "net/http"
)

type Book struct {
  Title  string `json:"title"`
  Author string `json:"author"`
}

func main() {
  http.HandleFunc("/", ShowBooks)
  http.ListenAndServe(":8080", nil)
}

func ShowBooks(w http.ResponseWriter, r *http.Request) {
  book := Book{"Building Web Apps with Go", "Jeremy Saenz"}

  js, err := json.Marshal(book)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }

  w.Header().Set("Content-Type", "application/json")
  w.Write(js)
}

Exercises

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文