panic:json:无法将数组解组为main类型的Go值. [英] panic: json: cannot unmarshal array into Go value of type main.Structure

查看:314
本文介绍了panic:json:无法将数组解组为main类型的Go值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析json api中的数据.

I am trying to parse data from a json api.

package main

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

type Structure struct {
        stuff []interface{}
}

func main() {
        url := "https://api.coinmarketcap.com/v1/ticker/?start=0&limit=100"
        response, err := http.Get(url)
        if err != nil {
                panic(err)
        }   
        body, err := ioutil.ReadAll(response.Body)
        if err != nil {
                panic(err)
        }   
        decoded := &Structure{}
        fmt.Println(url)
        err = json.Unmarshal(body, decoded)
        if err != nil {
                panic(err)
        }   
        fmt.Println(decoded)
}

您期望结果如何?

我希望代码返回接口对象列表.

What do you expect the result to be?

I expected for the code to return a list of interface objects.

我收到一个错误:panic: json: cannot unmarshal array into Go value of type main.Structure

推荐答案

应用程序正在将JSON数组解组到结构中.解组切片:

The application is unmarshalling a JSON array to a struct. Unmarshal to a slice:

 var decoded []interface{}
 err = json.Unmarshal(body, &decoded)

考虑解组为[] map [string]字符串或[] Tick所在的Tick,

Consider unmarshalling to a []map[string]string or a []Tick where Tick is

 type Tick struct {
     ID string
     Name string
     Symbol string
     Rank string
     ... and so on
}

这篇关于panic:json:无法将数组解组为main类型的Go值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆