drl9940 2017-09-10 07:45
浏览 58
已采纳

如何在golang中使用[] struct对象

I defined struct like:

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

that Unmarshal json string like

[{"data":"some data"}, {"data":"some data"}]

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

How i can use object of this struct for turn of data

  • 写回答

1条回答 默认 最新

  • dsjxgu4759 2017-09-10 08:02
    关注

    You can't use hyphens in type declarations, and you probably want to unmarshal to resp instead of resp.Data; that is, you may want to do something like

    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_

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?