我试着从网络读取 JSON 数据,但代码返回空结果。我不确定我在这里做错了什么。; H. p- q, c( \* b/ t6 d& U
package mainimport "os"import "fmt"import "net/http"import "io/ioutil"import "encoding/json"type Tracks struct Toptracks []Toptracks_info}type Toptracks_info struct Track []Track_info Attr []Attr_info}type Track_info struct Name string Duration string Listeners string Mbid string Url string Streamable []Streamable_info Artist Artist_info Attr Track_attr_info}type Attr_info struct Country string Page string PerPage string TotalPages string Total string}type Streamable_info struct Text string Fulltrack string}type Artist_info struct Name string Mbid string Url string}type Track_attr_info struct Rank string}func get_content() // json data url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands" res,err := http.Get(url) if err != nil panic(err.Error()body,err := ioutil.ReadAll(res.Body) if err != nil panic(err.Error()var data Tracks json.Unmarshal(body,&data) fmt.Printf("Results: %v\n",data) os.Exit(0)}func main() get_content()}9 P/ x! u- @" N
9 h. @; L; ?$ ^0 C6 o 解决方案: , ?" W; T3 L; H+ f+ j9 V6 I, N/ g
理想的方法不是使用ioutil.ReadAll,而是直接在阅读器上使用解码器。这是一个很好的函数,它获得 url 并将其响应解码到一个target结构上。7 J% S) Z' _7 ?) u3 K' D