为了账号安全,请及时绑定邮箱和手机立即绑定

如何在数组列表中保存[]byte数据

如何在数组列表中保存[]byte数据

Go
肥皂起泡泡 2023-08-14 16:58:17
总结一下问题我制作了一些从 toggl api 接收数据的应用程序。我尝试将 []byte 响应数据保存在 Go 的数组列表中,以便稍后修改数据。我想知道如何翻译此响应 []byte json 样式数据并将其存储为数组列表。显示一些代码主程序type togglData struct {}func GetTogglReports() []byte {    //some code    resp, err := client.Do(req)    if err != nil {        log.Fatal(err)    }    defer resp.Body.Close()    data, err := ioutil.ReadAll(resp.Body)    if err != nil {        log.Fatal(err)    }    return data}func makeSurveyText() {    // I want to save []byte data GetTogglReports() in array list here.    var togglData []togglData}数据是这样的: {    "total_grand":36004000,    "total_billable":14400000,    "total_currencies":[{"currency":"EUR","amount":40}],    "data": [      {        "id":193009951,        "title":{"project":"Toggl Development","client":null},        "time":14400000,        "total_currencies":[{"currency":"EUR","amount":0}],        "items":[          {            "title":{"time_entry":"Hard work"},            "time":14400000,            "cur":"EUR",            "sum":0,            "rate":50          }        ]      },{        "id":null,        "title":{"project":null,"client":null},        "time":7204000,        "total_currencies":[],        "items":[          {            "title":{"time_entry":"No title yet"},            "time":1000,            "cur":"EUR",            "sum":0,            "rate":50          }        ]      }    ]  }
查看完整描述

1 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

第一步将 JSON 转换为 go 结构。

type AutoGenerated struct {

    TotalGrand      int `json:"total_grand"`

    TotalBillable   int `json:"total_billable"`

    TotalCurrencies []struct {

        Currency string `json:"currency"`

        Amount   int    `json:"amount"`

    } `json:"total_currencies"`

    Data []struct {

        ID    int `json:"id"`

        Title struct {

            Project string      `json:"project"`

            Client  interface{} `json:"client"`

        } `json:"title"`

        Time            int `json:"time"`

        TotalCurrencies []struct {

            Currency string `json:"currency"`

            Amount   int    `json:"amount"`

        } `json:"total_currencies"`

        Items []struct {

            Title struct {

                TimeEntry string `json:"time_entry"`

            } `json:"title"`

            Time int    `json:"time"`

            Cur  string `json:"cur"`

            Sum  int    `json:"sum"`

            Rate int    `json:"rate"`

        } `json:"items"`

    } `json:"data"`

}

然后

  • 将 json 文件读入字节数组,即使用http.NewRequest("GET", url, nil),client.Do(req)byte_array,err:=ioutil.ReadAll(resp.Body)

  • 使用makenew创建结构体的实例

  • 将字节数组处理为结构体实例json.Unmarshal(byte_array, &instance_of_struct)

然后您将拥有一个包含 JSON 数据的结构


查看完整回答
反对 回复 2023-08-14
  • 1 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信