Go には、json 文字列を構造に簡単に解析したり、構造を json 文字列に解析したりできる組み込みencoding/json
パッケージが。
json 文字列を構造体に変換します。
json.NewDecoder(r.Body).Decode(&user)
構造体を JSON 文字列に変換します:
json.NewEncoder(w).Encode(peter)
構造体フィールドの後に追加することで
`json:“xxx” `
フィールドを特定の json フィールドに変換するため、それ以外の場合は元のフィールドとして出力されます。
完全なコード:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type User struct {
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
Age int `json:"age"`
}
func main() {
http.HandleFunc("/decode", func(w http.ResponseWriter, r *http.Request) {
var user User
json.NewDecoder(r.Body).Decode(&user)
fmt.Fprintf(w, "%s %s is %d years old!", user.Firstname, user.Lastname, user.Age)
})
http.HandleFunc("/encode", func(w http.ResponseWriter, r *http.Request) {
peter := User{
Firstname: "John",
Lastname: "Doe",
Age: 25,
}
json.NewEncoder(w).Encode(peter)
})
http.ListenAndServe(":8080", nil)
}
確認:
訪問/デコード | 訪問/エンコード |
---|---|