我正在制作一項向 Expo Backend 發送推送通知的服務。一旦發起 http 呼叫,Expo 就會以以下格式回應(根據 Expo):
{
"data": [
{
"status": "error" | "ok",
"id": string, // this is the Receipt ID
// if status === "error"
"message": string,
"details": JSON
},
...
],
// only populated if there was an error with the entire request
"errors": [{
"code": number,
"message": string
}]
}
這是一個提供的回應示例:
{
"data": [
{
"status": "error",
"message": "\\\"ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]\\\" is not a registered push notification recipient",
"details": {
"error": "DeviceNotRegistered"
}
},
{
"status": "ok",
"id": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
}
]
}
我創建了結構來解碼回應。現在我得到一個錯誤嘗試解碼“詳細資訊”欄位的回應,無論我在我的結構中使用什么型別。我該如何處理將 expo 標記為“JSON”的欄位?
import (
uuid "github.com/satori/go.uuid"
)
type PushResult struct {
Errors []ErrorDetails `json:"errors,omitempty"`
Datas []DataPart `json:"data,omitempty"`
}
type ErrorDetails struct {
Code int32 `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}
type DataPart struct {
Status string `json:"status,omitempty"`
ID uuid.UUID `json:"id,omitempty"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"` //also tried map[string]string and interface{}
}
這是我正在使用的結構。我還通過查看示例進行了嘗試:
type DataPart struct {
Status string `json:"status,omitempty"`
ID uuid.UUID `json:"id,omitempty"`
Message string `json:"message,omitempty"`
Details struct{
Error string `json:"error"`} `json:"details,omitempty"`
}
但是每次都會收到類似“json: cannot unmarshal object into Go struct field DataPart.data.details”之類的錯誤
uj5u.com熱心網友回復:
我剛剛使用您的回應示例創建了您的結構,它作業得很好。
操場
也就是說,如果您想要一種更好的方式來除錯“解組錯誤”,您可以打開它。這樣您就可以列印其他資料。
var t *json.UnmarshalTypeError
if errors.As(err, &t) {
spew.Dump(t)
}
示例-> 我將錯誤型別更改為整數,以便可以偽造錯誤。
OBS:請注意,您的“資料”是一個陣列,只有第一個有錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449302.html
