[英]Convert a slice of interface to an io.Reader object in golang?
I am trying to do this data conversion but I am stuck.我正在尝试进行此数据转换,但被卡住了。 I have this json request body:我有这个 json 请求正文:
{
"city": "XYZ",
"vouchers" :[
{
"voucherCode": "VOUCHERA",
"amount": 1000
},
{
"voucherCode": "VOUCHERB",
"amount":23
}
]
}
I want to get the vouchers
json array and pass it as a request payload to another API.我想获取vouchers
json 数组并将其作为请求有效负载传递给另一个 API。 Currently I am doing this to get the vouchers
array:目前我这样做是为了获取vouchers
数组:
type vouchers struct {
Vouchers []interface{} `json:"vouchers" form:"vouchers"`
}
vouchers := vouchers{}
json.Unmarshal(reqBody, &vouchers)
This gives me the vouchers
object but how do I convert this to an io.Reader
object and send it as a payload to another API?这为我提供了vouchers
对象,但如何将其转换为io.Reader
对象并将其作为有效负载发送到另一个 API?
Figured out one way to solve it, thanks to some help on the Discord Gophers channel.感谢 Discord Gophers 频道的帮助,找到了一种解决方法。 vouchers
json object can be unmarshalled into a field of type json.RawMessage
, which then can be passed in bytes.NewReader
. vouchers
json 对象可以解组到json.RawMessage
类型的字段中,然后可以在bytes.NewReader
传递。
type vouchers struct {
Vouchers json.RawMessage `json:"vouchers" form:"vouchers"`
}
vouchers := vouchers{}
json.Unmarshal(reqBody, &vouchers)
This can be later passed as a payload to another API using bytes.NewReader(vouchers.Vouchers)
.稍后可以使用bytes.NewReader(vouchers.Vouchers)
作为负载传递给另一个 API。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.