亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在數組列表中保存[]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 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號