1 回答

TA貢獻1827條經驗 獲得超4個贊
只需創建一個同時包含兩個字段的類型:
type MyType struct {
Foo *fooStruct `json:"foo,omitempty"`
Bar *barStruct `json:"bar,omitempty"`
OtherKey string `json:"other_key"`
}
將 JSON 解組為該類型,只需檢查 igFoo和 or Barare nil 即可了解您正在使用的數據。
這是一個 playground Demo,展示了它的樣子
它的本質是:
type Foo struct {
Field int `json:"field1"`
}
type Bar struct {
Message string `json:"field2"`
}
type Payload struct {
Foo *Foo `json:"foo,omitempty"`
Bar *Bar `json:"bar,omitempty"`
Other string `json:"another_field"`
}
和字段是指針類型,因為值字段會使確定實際設置Foo了Bar哪個字段變得更加麻煩。該omitempty位允許您編組相同的類型以重新創建原始有效負載,因為nil值不會顯示在輸出中。
要檢查原始 JSON 字符串中設置了哪個字段,只需編寫:
var data Payload
if err := json.Unmarshal([]byte(jsonString), &data); err != nil {
// handle error
}
if data.Foo == nil && data.Bar == nil {
// this is probably an error-case you need to handle
}
if data.Foo == nil {
fmt.Println("Bar was set")
} else {
fmt.Println("Foo was set")
}
- 1 回答
- 0 關注
- 156 瀏覽
添加回答
舉報