此问题在此处已有答案:
Convert byte slice to io.Reader(1个答案)
2天前关闭。
我有一个主体响应,我只能得到字节响应。这个字节编码了一个类似csv的响应。类似于:
element_a,element_b,element_c
cooper,claus,active
carlos,saldanha,inactive
robert,jesus,active
假设我有这样的结构体:
type ESResponse struct {
ElementA string `csv:"element_a"`
ElementB string `csv:"element_b"`
ElementC string `csv:"element_c"`
}
我想对字节响应进行反编组,这样我就可以访问它的元素了。
我一直在做的事情如下:
var actualResult ESResponse
body := util.GetResponseBody() // this is where the byte response comes from.
in := string(body[:]) // here I transform it to a string but I trully think this is not the best way.
err = gocsv.Unmarshal(in, &actualResult)
我一直在用这个图书馆:https://pkg.go.dev/github.com/gocarina/gocsv#section-readme,但我无法理解我得到的错误是:
cannot use in (variable of type string) as io.Reader value in argument to gocsv.Unmarshal: string does not implement io.Reader (missing method Read)
1条答案
按热度按时间omtl5h9j1#
这意味着,
in
参数必须实现接口io.Reader,但是你的参数类型是string,而不是,所以如果你想从string反序列化value,你可以这样做:或
gocsv.Unmarshal(bytes.NewReader([]byte(body)), &actualResult)
从字节数组反序列化