I'm new in Golang, and have a problem. I use package github.com/astaxie/beego/httplib
, try to get info from API
res := httplib.Get("example.com")
type SomeStruct struct {
Type string
Id string
// ...
}
var itemStruct SomeStruct
err := res.ToJSON(&itemStruct)
Problem: in API response Id field might be string or number (depending on Type field), thats why I get error json: cannot unmarshal number into Go value of type string
. I think, I must filter response before ToJSON method. Or I must create struct with only field Type, get data from API, filter by Type. But in this case how can I get other fields? Thanks
Would it work to make Type
of type interface{}
?
Casting in go is quite clean so you could then iterate and cast when you are using the type
for _, s := ss {
switch v := s.Type.(type) {
case string:
// Do something
cast int:
// Do something else
default:
// Handle unexpected type gracefully.
}
}