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

总结一下问题

我制作了一些从 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

          }

        ]

      }

    ]

  }



肥皂起泡泡
浏览 67回答 1
1回答

缥缈止盈

第一步将 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)使用make或new创建结构体的实例将字节数组处理为结构体实例json.Unmarshal(byte_array, &instance_of_struct)然后您将拥有一个包含 JSON 数据的结构
打开App,查看更多内容
随时随地看视频慕课网APP