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 关注
- 249 浏览
添加回答
举报
