亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解析嵌套在表單 urlencoded POST 中的 JSON 字符串

解析嵌套在表單 urlencoded POST 中的 JSON 字符串

Go
三國紛爭 2023-07-31 17:02:50
我正在嘗試解析 Mailgun 通知 Webhook 的一部分。這是一個帶有x-www-form-urlencoded正文的 POST 請求。這是身體的一部分:sender: [email protected]: [{"url": "https://storage.eu.mailgun.net/v3/domains/beep.boop/messages/randomstring/attachments/0", "content-type": "application/pdf", "name": "example.pdf", "size": 345}]"]該attachments值是一個json編碼數組我想將這個字符串從 JSON 解碼為StoredAttachment嵌套結構,因為我正在解碼響應,x-www-form-urlencoded但我不知道該怎么做。目標structs如下:type NotifiedMessage struct {    Sender      string `schema:"sender"`    Subject     string `schema:"subject"`    Attachments []StoredAttachment `schema:"attachments"`    MessageUrl  string `schema:"message-url"`}// StoredAttachment structures contain information on an attachment associated with a stored message.type StoredAttachment struct {    Size        int    `json:"size"`    Url         string `json:"url"`    Name        string `json:"name"`    ContentType string `json:"content-type"`}這是到目前為止我的非工作代碼:https ://play.golang.org/p/Ofbw2VAYV28
查看完整描述

1 回答

?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

您可以實現該TextUnmarshaler接口,schema包將使用該接口而不是執行默認過程,這允許自定義解組。


1.聲明一個命名類型并將其用作字段的類型Attachments。[]StoredAttachment是未命名的。因此,例如:

type AttachmentList []StoredAttachment

為什么?因為方法只能在命名類型上聲明。

2.實現TextUnmarhsaler接口并在那里進行 json 解壓縮。

func (ls *AttachmentList) UnmarshalText(text []byte) (err error) {
    return json.Unmarshal(text, (*[]StoredAttachment)(ls))
}

就是這樣。

https://play.golang.org/p/t65mI7JRFfS


查看完整回答
反對 回復 2023-07-31
  • 1 回答
  • 0 關注
  • 171 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號