假设我有一个以两种不同格式接收json数据的应用程序.
f1 = `{"pointtype":"type1", "data":{"col1":"val1", "col2":"val2"}}`
f2 = `{"pointtype":"type2", "data":{"col3":"val3", "col3":"val3"}}`
Run Code Online (Sandbox Code Playgroud)
我有一个与每种类型相关联的结构:
type F1 struct {
col1 string
col2 string
}
type F2 struct {
col3 string
col4 string
}
Run Code Online (Sandbox Code Playgroud)
假设我使用encoding/json
库将原始json数据转换为struct:type Point {pointtype string data json.RawMessage}
如何通过了解点类型将数据解码为适当的结构?
我正在尝试以下方面:
func getType(pointType string) interface{} {
switch pointType {
case "f1":
var p F1
return &p
case "f2":
var p F2
return &p
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
哪个不起作用,因为返回的值是一个接口,而不是正确的结构类型.如何使这种开关结构选择工作?
您可以在从方法返回的接口上键入switch:
switch ps := parsedStruct.(type) {
case *F1:
log.Println(ps.Col1)
case *F2:
log.Println(ps.Col3)
}
Run Code Online (Sandbox Code Playgroud)
..等等.请记住,要encoding/json
正确解码包(通过反射),您的字段需要导出(大写第一个字母).
工作样本:http://play.golang.org/p/8Ujc2CjIj8