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 |
|---|---|
![]() | ![]() |
本文介绍如何使用Go语言内置的encoding/json包将JSON字符串解析为结构体或将结构体转换为JSON字符串。通过示例代码展示了如何定义结构体字段的JSON标签,并提供HTTP请求处理函数来演示解析和生成JSON的过程。


469

被折叠的 条评论
为什么被折叠?



