Let's say I have an application that receives json data in two different formats.
f1 = `{"pointtype":"type1", "data":{"col1":"val1", "col2":"val2"}}`
f2 = `{"pointtype":"type2", "data":{"col3":"val3", "col3":"val3"}}`
And I have a struct associated to each type:
type F1 struct {
col1 string
col2 string
}
type F2 struct {
col3 string
col4 string
}
Assuming that I use the encoding/json
library to turn the raw json data into the struct:
type Point {
pointtype string
data json.RawMessage
}
How can I decode the data into the appropiate struct just by knowing the pointtype?
I was trying something along the lines of :
func getType(pointType string) interface{} {
switch pointType {
case "f1":
var p F1
return &p
case "f2":
var p F2
return &p
}
return nil
}
Which is not working because the returned value is an interface, not the proper struct type. How can I make this kind of switch struct selection work?