业余时间玩 Golang。尝试执行典型的 Web 任务:从 GET 请求中获取 json 并打印其值。type Weather struct { name string}// some codedecoder := json.NewDecoder(res.Body)for { var weather Weather if err := decoder.Decode(&weather); err == io.EOF { break } else if err != nil { log.Fatal(err) } fmt.Println(weather.name) }JSON:{"coord":{"lon":145.77,"lat":-16.92},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"base":"stations","main":{"temp":300.15,"pressure":1007,"humidity":74,"temp_min":300.15,"temp_max":300.15},"visibility":10000,"wind":{"speed":2.6,"deg":260},"clouds":{"all":20},"dt":1455633000,"sys":{"type":1,"id":8166,"message":0.0314,"country":"AU","sunrise":1455567124,"sunset":1455612583},"id":2172797,"name":"Cairns","cod":200}据我了解,我需要声明一个结构来获取 json 值,但它不打印任何内容。我的错误是什么?如果我需要操作带有未知字段的json怎么办?有没有办法直接从json构造地图?
1 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
您结构中的“名称”字段Weather未导出。必须为其他包导出字段类型才能看到它们(因此,解组/解码到它们中):https : //tour.golang.org/basics/3
您也可以使用结构标记将 Go 字段名称映射到 JSON 键:
type Weather struct {
Name string `json:"name"`
}
...而在未来,您可以使用https://mholt.github.io/json-to-go/从 JSON 自动生成 Go 结构。
- 1 回答
- 0 关注
- 202 浏览
添加回答
举报
0/150
提交
取消
