Golang如何读取JSON格式的API响应体

Golang如何读取JSON格式的API响应体 我想读取POST请求的JSON主体

type MyData struct {
grant_type string `json:"grant_type"`
username  string  `json:"username"`
password string	  `json:"password"`
}
func main() {
http.HandleFunc("/", requestHandler)
log.Fatal(http.ListenAndServe("127.0.0.1:8085", nil))
}
func requestHandler(w http.ResponseWriter, r *http.Request) {

decoder := json.NewDecoder(r.Body)
var t MyData
err := decoder.Decode(&t)
if err != nil{
	panic(err)
}
fmt.Print("======================================>>>>>>>>>>>>>>>>",decoder)

更多关于Golang如何读取JSON格式的API响应体的实战教程也可以访问 https://www.itying.com/category-94-b0.html

5 回复

将结构体的字段公开,否则 JSON 无法识别它们。

更多关于Golang如何读取JSON格式的API响应体的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


通过 Postman 发送的 JSON 数据:

{
"grant_type": "password",
"username": "m",
"password": "Password"
}

基于 @NobbZ 的回答进行补充,在你的 MyData 类型中,需要将字段名改为以大写字母开头,如下所示:

type MyData struct {
  GrantType string json:"grant_type"
  Username string json:"username"
  Password string json:"password"
}

encoding/json 包不会填充未导出的字段。

不,我不是那个意思。

我的意思是,你需要将想要进行序列化/反序列化的结构体字段公开。

如果字段没有公开,JSON(反)序列化器将无法看到和操作这些字段。

@joncalhoun 很好地解释了如何实现这一点

要正确读取JSON格式的API响应体,你的代码有几个问题需要修复。主要问题包括结构体字段需要导出(首字母大写),以及需要正确处理JSON解码后的数据。

以下是修正后的代码:

type MyData struct {
    GrantType string `json:"grant_type"`
    Username  string `json:"username"`
    Password  string `json:"password"`
}

func requestHandler(w http.ResponseWriter, r *http.Request) {
    // 检查请求方法
    if r.Method != http.MethodPost {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }

    // 设置响应头
    w.Header().Set("Content-Type", "application/json")

    decoder := json.NewDecoder(r.Body)
    var t MyData
    err := decoder.Decode(&t)
    if err != nil {
        http.Error(w, "Invalid JSON format", http.StatusBadRequest)
        return
    }
    
    // 使用解码后的数据
    fmt.Printf("Grant Type: %s\n", t.GrantType)
    fmt.Printf("Username: %s\n", t.Username)
    fmt.Printf("Password: %s\n", t.Password)
    
    // 返回响应
    response := map[string]string{"status": "success"}
    json.NewEncoder(w).Encode(response)
}

func main() {
    http.HandleFunc("/", requestHandler)
    log.Fatal(http.ListenAndServe("127.0.0.1:8085", nil))
}

如果你想要更简洁的方式,也可以使用json.Unmarshal

func requestHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }

    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Error reading request body", http.StatusInternalServerError)
        return
    }

    var t MyData
    err = json.Unmarshal(body, &t)
    if err != nil {
        http.Error(w, "Invalid JSON format", http.StatusBadRequest)
        return
    }

    fmt.Printf("Received data - GrantType: %s, Username: %s\n", t.GrantType, t.Username)
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]string{"message": "Data received successfully"})
}

关键修改点:

  1. 结构体字段改为首字母大写(GrantType, Username, Password)
  2. 添加了错误处理和适当的HTTP状态码
  3. 移除了panic,改用更合适的错误处理
  4. 添加了响应头设置
  5. 提供了JSON响应输出
回到顶部