3 回答

TA貢獻1963條經驗 獲得超6個贊
最簡單的可能是處理所有可能的字段并進行一些后處理。
例如:
type MyType struct {
DateField1 []string `xml:"value"`
DateField2 []string `xml:"anotherValue"`
}
// After parsing, you have two options:
// Option 1: re-assign one field onto another:
if !someCondition {
parsed.DateField1 = parsed.DateField2
parsed.DateField2 = nil
}
// Option 2: use the above as an intermediate struct, the final being:
type MyFinalType struct {
Date []string `xml:"value"`
}
if someCondition {
final.Date = parsed.DateField1
} else {
final.Date = parsed.DateField2
}
注意:如果消息差異很大,您可能需要完全不同的類型進行解析。后處理可以從其中任何一個生成最終結構。

TA貢獻1818條經驗 獲得超11個贊
如前所述,您必須復制該字段。問題是重復應該存在于何處。
如果它只是多個字段中的一個,一種選擇是使用嵌入和字段陰影:
type MyType struct {
Date []string `xml:"value"`
// many other fields
}
然后當Date使用其他字段名稱時:
type MyOtherType struct {
MyType // Embed the original type for all other fields
Date []string `xml:"anotherValue"`
}
然后在解組之后MyOtherType,很容易將Date值移動到原始結構中:
type data MyOtherType
err := json.Unmarshal(..., &data)
data.MyType.Date = data.Date
return data.MyType // will of MyType, and fully populated
請注意,這僅適用于解組。如果您還需要編組這些數據,可以使用類似的技巧,但圍繞它的機制必須從本質上顛倒過來。
- 3 回答
- 0 關注
- 157 瀏覽
添加回答
舉報