Go通过encoding/json和net/http包处理JSON,需定义可导出字段的结构体并用tag映射JSON键名,解析时检查Content-Type并用json.NewDecoder读取请求体,返回时设置Header为application/json并用json.NewEncoder输出,支持嵌套结构与map处理复杂数据。

在Golang中处理JSON请求与响应是构建Web服务的基础能力,尤其是在开发API接口时非常常见。Go标准库中的 encoding/json 和 net/http 包提供了强大且简洁的支持。下面介绍如何正确地接收JSON请求并返回JSON响应。
Go通过结构体(struct)来解析和生成JSON数据。使用结构体字段标签(tag)指定JSON字段名。
例如,处理用户注册请求:
type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
    Age   int    `json:"age,omitempty"` // omitempty 表示当字段为零值时忽略输出
}
结构体字段必须是可导出的(首字母大写),否则 json.Unmarshal 无法赋值。
在HTTP处理器中,从请求体读取JSON数据并解析到结构体。
立即学习“go语言免费学习笔记(深入)”;
func handleRegister(w http.ResponseWriter, r *http.Request) {
    if r.Header.Get("Content-Type") != "application/json" {
        http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
        return
    }
    var user User
    decoder := json.NewDecoder(r.Body)
    defer r.Body.Close()
    if err := decoder.Decode(&user); err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }
    // 此处可添加业务逻辑,如保存用户
    log.Printf("Received user: %+v", user)
}
注意检查 Content-Type 防止非JSON数据提交,同时使用 defer 关闭请求体。
                        
                        Easily find JSON paths within JSON objects using our intuitive Json Path Finder
                                30
                            
                        
                    向客户端返回结构化JSON数据时,设置正确的响应头并编码输出。
func handleProfile(w http.ResponseWriter, r *http.Request) {
    user := User{
        Name:  "Alice",
        Email: "alice@example.com",
        Age:   28,
    }
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(user)
}
使用 w.Header().Set 设置 content-type,避免浏览器或客户端解析错误。Encode 自动处理序列化,无需手动调用 Marshal。
对于嵌套对象或动态字段,结构体可以包含结构体或 map。
type Address struct {
    City  string `json:"city"`
    Zip   string `json:"zip"`
}
type UserProfile struct {
    User     User              `json:"user"`
    Address  Address           `json:"address"`
    Metadata map[string]string `json:"metadata,omitempty"`
}
map 类型适合处理不确定字段的JSON,比如第三方回调数据。
基本上就这些。只要结构体定义清晰、请求体正确解析、响应头设置得当,Golang处理JSON就很直观。不复杂但容易忽略细节,比如类型匹配和错误处理。
以上就是如何在Golang中处理JSON请求与响应的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号