What am I going to do :
I have some API which response Json format data.Fields in every API are different and I just need a few data.So I prepared some struct for every API to filter out the data I need.
What’s the issue:
Due to many different struct‘s existence,When I was ready to use
json.Unmarshal
,I had to passinterface
.But when I usinginterface
,I found the result ismap
,and all of the data from the API are in themap
,which caused mystruct
for API (filter some data) did’t work.
For instance:
type API struct {
MyTarget string `json:"target"`
}
type API2 struct {
MyTarget2 string `json:"target2"`
}
type API3 struct {
MyTarget3 string `json:"target3"`
}
var APISlice = map[string]interface{}{
"api":API{},
"api2":API2{},
"api3":API3{},
}
func main() {
data = []byte{xxxxx} //from API response
str := "api1" //assume it's api1,I will range every API when I really work
myStruct := APISlice[str]
json.Unmarshal(data,&myStruct)
//now the result is a map which include all the data from API. sad.........
}
What I really want is the data can be unmarshal into the struct so that I can get the data I have defined in struct.
How to unmarshal data into the specific struct (Is it possiable?)?
Or can I get the data I want through json.Unmarshal(data,interface)
?