首页 > 解决方案 > 如何在 Go 中解组 Json 数组

问题描述

我正在努力解析以下 json 数据:

[{"id":90129966,"from":"user@admin.com","subject":"golang test","date":"2020-10-20 07:39:55"}]

这是我的代码:

package main

import (
    "encoding/json"
    "fmt"
)

type JsonTemplate struct {
    Id      int    `json:"id"`
    From    string `json:"from"`
    Subject string `json:"subject"`
    Date    string `json:"date"`
}

type Response struct {
    JsonTemplate []JsonTemplate
}


func main() {

    mockJson := `[{"id":90129966,"from":"user@admin.com","subject":"golang test","date":"2020-10-20 07:39:55"}]`

    var response Response

    err := json.Unmarshal([]byte(mockJson), &response)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(response)
}

输出:

json: cannot unmarshal array into Go value of type main.Response
{[]}

我不知道我在这里做错了什么。有人能指出我正确的方向吗?

标签: jsongo

解决方案


从 Flimzy 那里得到了答案:var response []JsonTemplate。再次感谢。


推荐阅读