1 回答

TA貢獻1784條經驗 獲得超9個贊
類型 ResArray 結構 {
但它不是結構,而是切片!
type LastArray struct {
Info string
}
但它不是字符串,有時是字符串,有時是數字。
執行此操作的簡單方法是將您的類型定義為
type Equipment struct {
Results [][]interface{}
}
它說結果包含一片……某物。您可以命名中間類型,但這不是必需的。那么例如e.Results[0][1].(string)將是"Zho's Mask"。
更好的方法是通過提供一個 custom來實現UnmarshalerUnmarshalJSON接口,如下所示:
type Equipment struct {
Results []Item
}
type Item struct {
ID int
Name string
Sell int
}
func (i *Item) UnmarshalJSON(b []byte) error {
// We're deserializing into a struct, but in JSON it's a mixed-type array.
var arr []interface{}
err := json.Unmarshal(b, &arr)
if err != nil {
return fmt.Errorf("unmarshal Item underlying array: %w", err)
}
if len(arr) != 3 {
return fmt.Errorf("Item underlying array should be 3 elements, got %d", len(arr))
}
// JSON numbers will become float64 when loaded into interface{} but we want int
id, ok := arr[0].(float64)
if !ok {
return fmt.Errorf("expected float64 for Item.ID, got %T", arr[0])
}
i.ID = int(id)
i.Name, ok = arr[1].(string)
if !ok {
return fmt.Errorf("expected string for Item.Name, got %T", arr[1])
}
sell, ok := arr[2].(float64)
if !ok {
return fmt.Errorf("expected float64 for Item.Sell, got %T", arr[2])
}
i.Sell = int(sell)
return nil
}
請記住,這些類型與您向 API 請求的確切字段列表結合在一起——如果您更改它,您將不得不更改類型和從數組加載它的解組函數。
- 1 回答
- 0 關注
- 221 瀏覽
添加回答
舉報