【问题标题】:How use object of []struct in golanggolang中如何使用[]struct的对象
【发布时间】:2018-02-18 16:14:07
【问题描述】:

我定义了这样的结构:

type json-input []struct {
    Data    string  `json:"data"`
}

这样的 Unmarshal json 字符串

[{"数据":"一些数据"}, {"数据":"一些数据"}]

data := &json-input{}
_ = json.Unmarshal([]byte(resp.Data), data)

我如何使用这个结构的对象来转换数据

【问题讨论】:

    标签: go struct slice


    【解决方案1】:

    你不能在类型声明中使用连字符,你可能想解组到resp而不是resp.Data;也就是说,您可能想要做类似的事情

    import (
        "encoding/json"
        "fmt"
    )
    
    type jsoninput []struct {
        Data string `json:"data"`
    }
    
    func main() {
        resp := `[{"data":"some data"}, {"data":"some more data"}]`
        data := &jsoninput{}
        _ = json.Unmarshal([]byte(resp), data)
        for _, value := range *data {
            fmt.Println(value.Data)  // Prints "some data" and "some more data"
        }
    }
    

    https://play.golang.org/p/giDsPzgHT_

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 2016-10-13
      相关资源
      最近更新 更多