1 回答

TA貢獻1841條經驗 獲得超3個贊
你能控制不同的反應嗎?如果是這樣,要不要在頂層添加一個“類型”字段?
有關詳細信息,請參閱https://eagain.net/articles/go-dynamic-json/上的“如何將所有內容放在頂層”部分。
例如(未經測試):
func UnmarshalJSON(d []byte) error {
var jsonValue map[string]interface{}
err := json.Unmarshal(d, &jsonValue)
if err != nil {
return err
}
switch jsonValue["type"] {
case 1:
// unmarshal into struct type 1
case 2:
// unmarshal into struct type 2
default:
// throw err
}
// or if you don't have access to type:
if jsonValue["connectionID"] != nil {
// unmarshal into struct type 1
}
return nil
}
或者,您可以嘗試(嚴格)解組到每個結構中,直到您沒有收到錯誤,例如:
func DetermineStruct(d []byte) int {
var connStatus *ConnStatus
reader := bytes.NewReader(d)
decoder := json.NewDecoder(reader)
decoder.DisallowUnknownFields()
err := decoder.Decode(connStatus)
if err == nil {
panic(err)
}
err = json.Unmarshal(d, &connStatus)
if err == nil {
return 1
}
var ohlcSuccess OHLCsuccess
err = json.Unmarshal(d, &ohlcSuccess)
if err == nil {
return 2
}
}
- 1 回答
- 0 關注
- 141 瀏覽
添加回答
舉報