You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go后端开发:JSON反序列化报错问题求助

解决Go JSON反序列化错误:无法将对象反序列化为切片类型

错误原因

你遇到的json: cannot unmarshal object into Go value of type []main.LocationData错误,核心是数据类型不匹配:

  • API返回的是单个JSON对象(包含locations字段的对象)
  • 你的代码试图把它解析成对象切片[]LocationData,类型不兼容导致反序列化失败

修正方案

1. 调整解析目标类型

将getLocationData函数中的解析目标从[]LocationData改为LocationData,匹配API返回的单个对象结构。

2. 修正后的完整代码示例

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

const (
    locationsURL = "https://groupietrackers.herokuapp.com/api/locations"
)

type LocationData struct {
    Locations []string `json:"locations"`
}

// fetchDataFromURL 发起HTTP请求并读取响应体
func fetchDataFromURL(url string) ([]byte, error) {
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    return body, nil
}

// getLocationData 解析API返回的位置数据
func getLocationData() (LocationData, error) {
    var data LocationData
    body, err := fetchDataFromURL(locationsURL)
    if err != nil {
        return LocationData{}, err
    }
    if err := json.Unmarshal(body, &data); err != nil {
        return LocationData{}, fmt.Errorf("failed to decode response body: %w", err)
    }
    return data, nil
}

// homeHandler 处理首页请求并渲染模板
func homeHandler(w http.ResponseWriter, r *http.Request) {
    locationData, err := getLocationData()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 传递locationData到模板渲染(示例)
    // err := yourTemplate.Execute(w, locationData)
    // if err != nil {
    //     http.Error(w, "failed to render template", http.StatusInternalServerError)
    // }
}

3. 验证逻辑

API返回的JSON结构为:

{"locations":["north_carolina-usa","georgia-usa","los_angeles-usa","saitama-japan","osaka-japan","nagoya-japan","penrose-new_zealand","dunedin-new_zealand"]}

该结构与你定义的LocationData结构体完全匹配,使用单个结构体实例接收即可完成正确反序列化,无需使用切片。

内容的提问来源于stack exchange,提问作者ali mahdi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 18:10:05