英文:
Convert a slice of interface to an io.Reader object in golang?
问题
我正在尝试进行数据转换,但是遇到了困难。我有以下的JSON请求体:
{
"city": "XYZ",
"vouchers" :[
{
"voucherCode": "VOUCHERA",
"amount": 1000
},
{
"voucherCode": "VOUCHERB",
"amount":23
}
]
}
我想获取vouchers
的JSON数组,并将其作为请求有效载荷传递给另一个API。目前我正在使用以下代码获取vouchers
数组:
type vouchers struct {
Vouchers []interface{} `json:"vouchers" form:"vouchers"`
}
vouchers := vouchers{}
json.Unmarshal(reqBody, &vouchers)
这样可以得到vouchers
对象,但是如何将其转换为io.Reader
对象并将其作为有效载荷发送给另一个API呢?
英文:
I am trying to do this data conversion but I am stuck. I have this json request body:
{
"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. Currently I am doing this to get the vouchers
array:
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?
答案1
得分: 3
找到了一种解决方法,感谢 Discord Gophers 频道上的一些帮助。vouchers
的 JSON 对象可以解组成一个类型为 json.RawMessage
的字段,然后可以通过 bytes.NewReader
传递。
type vouchers struct {
Vouchers json.RawMessage `json:"vouchers" form:"vouchers"`
}
vouchers := vouchers{}
json.Unmarshal(reqBody, &vouchers)
稍后可以将其作为有效载荷传递给另一个 API,使用 bytes.NewReader(vouchers.Vouchers)
。
英文:
Figured out one way to solve it, thanks to some help on the Discord Gophers channel. vouchers
json object can be unmarshalled into a field of type json.RawMessage
, which then can be passed in 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)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论