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
相关产品推荐
相关产品推荐

