[英]Convert interface{} to struct in Golang
我對 Go 很陌生,我正在努力了解所有不同的類型以及如何使用它們。 我有一個包含以下內容的界面(最初在一個 json 文件中):
[map[item:electricity transform:{fuelType}] map[transform:{fuelType} item:gas]]
我有以下結構
type urlTransform struct {
item string
transform string
}
我不知道如何將接口數據放入結構中; 我敢肯定這真的很愚蠢,但我一整天都在嘗試。 任何幫助將不勝感激。
將 JSON 直接解碼為您想要的類型,而不是解碼為interface{}
。
聲明與 JSON 數據結構匹配的類型。 對 JSON 對象使用結構體,對 JSON 數組使用切片:
type transform struct {
// not enough information in question to fill this in.
}
type urlTransform struct {
Item string
Transform transform
}
var transforms []urlTransform
必須導出字段名稱(以大寫字母開頭)。
將 JSON 解組為聲明的值:
err := json.Unmarshal(data, &transforms)
或者
err := json.NewDecoder(reader).Decode(&transforms)
根據您的回復: [map[item:electricity transform:{fuelType}] map[transform:{fuelType} item:gas]]
。 正如你在這里看到的,這是一個包含map
的array
。
從中獲取價值的一種方法是:
values := yourResponse[0].(map[string]interface{}). // convert first index to map that has interface value.
transform := urlTransform{}
transform.Item = values["item"].(string) // convert the item value to string
transform.Transform = values["transform"].(string)
//and so on...
正如您從上面的代碼中看到的,我正在使用 map 獲取值。 在這種情況下,將值轉換為適當的類型是string
。
您可以將其轉換為適當的類型,如int
或bool
或其他類型。 但是這種方法很痛苦,因為您需要一一獲取值並將其分配給您的字段結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.