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 关注
- 147 浏览
添加回答
举报