1 回答

TA貢獻1828條經驗 獲得超3個贊
如果在編譯時沒有指定它,您仍然需要在某處指定它。
如果在檢索 Json 數據之前指定,您可以簡單地做一個 switch case,將它解組到您想要的對象。
如果在Json 數據中指定,則可以json.RawMessage在確定適合哪種類型的結構后將“靈活”部分編組到 a 中以進行處理:
package main
import (
"encoding/json"
"fmt"
)
var s = `{"type":"structx", "data":{"x":9,"xstring":"This is structX"}}`
type JsonStruct struct {
Type string
Data json.RawMessage
}
type StructX struct {
X float64
Xstring string
}
type StructY struct {
Y bool
}
func main() {
var a *JsonStruct
err := json.Unmarshal([]byte(s), &a)
if err != nil {
panic(err)
}
switch a.Type {
case "structx":
// We Unmashal the RawMessage part into a StructX
var s *StructX
json.Unmarshal([]byte(a.Data), &s)
if err != nil {
panic(err)
}
fmt.Println(s)
case "structy":
// Do the same but for structY
}
}
- 1 回答
- 0 關注
- 167 瀏覽
添加回答
舉報