简体   繁体   中英

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:

{
    "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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM