ioutil.ReadAll 和 unmarshal 对嵌套的 curl 响应返回错误

为了给你上下文,我正在卷曲到第三方端点,响应类似于这个


{

    "code": 200,

    "message": "Success",

    "data": {

        "list": [

            {

               "user": "user A",

               "status" : "normal"

            },

            {

                "user": "user B",

               "status" : "normal"

            }

        ],

        "page": 1,

        "total_pages": 5000

    }

}

我的结构类似于


type User struct {

    Code    int    `json:"code"`

    Message string `json:"message"`

    Data    struct {

        List []struct {

            User   string `json:"user"`

            Status string `json:"status"`

        } `json:"list"`

        Page       int `json:"page"`

        TotalPages int `json:"total_pages"`

    } `json:"data"`

}

请检查我的代码


defer response.Body.Close()

io_response, err := ioutil.ReadAll(response.Body)


returnData := User{}

err = jsoniter.Unmarshal([]byte(io_response), &returnData)

if err != nil {

   log.Println(err)

}

上面的代码返回错误


decode slice: expect [ or n, but found {, error found in #10 byte of ...|:{"list":{"1"

当我执行 fmt.Println(string(io_response)) 时,返回结果如下:


{ "code": 200, "message": "成功", "data": { "list": { "1": { "user": "user A", "status": "normal" }, "2 ": { "user": "user A", "status": "normal" } }, "page": 1, "total_pages": 2000 } }


你能教我如何正确阅读回复或如何解组吗?谢谢


慕村225694
浏览 173回答 1
1回答

绝地无双

你可以这样定义你的结构:type User struct {    Code    int    `json:"code"`    Message string `json:"message"`    Data    struct {        List map[string]struct {            User   string `json:"user"`            Status string `json:"status"`        } `json:"list"`        Page       int `json:"page"`        TotalPages int `json:"total_pages"`    } `json:"data"`}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go