我正在開發一個 RESTful API,需要確定用戶發送了什么。假設這是 JSON 格式的 POST 請求的主體:{ "request": "reset-users", "parameters": [ { "users": ["userA","userB","userC"] } ]}使用json.Unmarshal,我將正文讀入這個標準化結構:type RequestBody struct { Request string `json:"request"` Parameters []map[string]interface{} `json:"parameters"`}所以,現在,我可以requestBody.Parameters[0]["users"]使用以下類型斷言開關塊檢查類型:switch requestBody.Parameters[0]["users"].(type) { case []interface {}: //It is actually a list of some type default: //Other types}上面提到的代碼有效,但我如何才能確定某種類型的列表是字符串列表?(相對于 int 或 bool 的列表...)
2 回答

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
當解組為 時interface{}
,標準庫解組器總是使用以下內容:
map[string]interface{}
對于對象[]interface{}
對于數組string
,bool
,float64
,nil
對于值
因此,當您獲得 a 時[]interface{}
,它是一個數組,其元素可以是上述任何一種類型。您必須遍歷每個并鍵入斷言:
switch v:=requestBody.Parameters[0]["users"].(type) {
case []interface {}:
for _,x:=range v {
if s, ok:=x.(string); ok {
// It is a string
}
}
...
}

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
文檔清楚地說明了它將使用什么類型:“[]interface{}, for JSON arrays”。它將始終是[]interface{}
,這是一個具體類型,不能斷言為任何其他類型;不可能[]string
,因為那是與 不同的類型[]interface{}
。的每個元素都[]interface{}
可以是文檔中列出的任何類型,具體取決于原始 JSON 數組的每個元素的類型。
- 2 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消