Convert a slice of interface to an io.Reader object in golang?

huangapple go评论85阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2021年10月19日 17:46:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/69628597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定