我正在从服务器读取 API (JSON) 响应,我应该得到(如果状态为 200 ok)以下响应。
// If I sent a wrong data ..
{
error: "some value",
message: "... description of the error"
}
或
// if all is good
{
events: [{key1: 1}, {key2: "two"} ... ]
}
因为我不确定响应的类型。
我正在将响应解码为 map[string]interface{}
。
resp := make(map[string]interface{}, 0)
json.NewDecoder(response.Body).Decode(&resp)
在代码流的后面,我到达了一个阶段,我知道响应是一个很好的阶段。我需要将 interface{}
类型转换回 []map[string]interface{}
。
但我认为这行不通..
// This does not work I guess.
// events := resp["events"].([]map[string]interface{})
我设法做到这一点的唯一明智的方法是使用。
interFace := resp["events"].([]interface{})
for mapInterface := range interFace {
row := MapInterface.(map[string]interface{})
// now use the row hence forth
}
是否可以通过任何其他方式或任何其他方法1 避免在循环内强制转换来完成此操作。
1:也许在这里创建一个 Response 结构可行。但我真的很想听听在使用 struct
方法之前我可以尝试的任何其他方法。
最佳答案
您可以定义一个在结构中同时具有错误值和非错误值的结构。
type Response struct {
ErrorMessage string `json:"message"`
Error string `json:"error"`
Events []map[string]interface{} `json:"events"`
}
关于go - 避免在循环中对 slice 值进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51825482/