Go内置了 encoding/json
包可以很方便的将json字符串解析成结构体,或者将结构体解析成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)
}
验证:
访问/decode | 访问/encode |
---|---|
![]() | ![]() |