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 structure associated with each type:
type F1 struct {
col1 string
col2 string
}
type F2 struct {
col3 string
col4 string
}
Assuming I am using a library encoding/jsonto turn json source data into struct: type Point {string of type pointtype json.RawMessage data}
How can I decode data in a suitable structure, just knowing the type of point?
I tried to do something like this:
func getType(pointType string) interface{} {
switch pointType {
case "f1":
var p F1
return &p
case "f2":
var p F2
return &p
}
return nil
}
Which does not work, because the return value is an interface, not the corresponding type of structure. How can I make this switch structure selection function?
here is a non-working example
source
share