我需要解组 json 对象,它可能具有以下格式:
格式1:
{
"contactType": 2,
"value": "0123456789"
}
Run Code Online (Sandbox Code Playgroud)
格式2:
{
"contactType": "MobileNumber",
"value": "0123456789"
}
Run Code Online (Sandbox Code Playgroud)
我用于解组的结构是:-
type Contact struct {
ContactType int `json:"contactType"`
Value string `json:"value"`
}
Run Code Online (Sandbox Code Playgroud)
但这仅适用于格式 1。我不想更改 ContactType 的数据类型,但我也想适应第二种格式。我听说过 json.RawMarshal 并尝试使用它。
type Contact struct {
ContactType int
Value string `json:"value"`
Type json.RawMessage `json:"contactType"`
}
type StringContact struct {
Type string `json:"contactType"`
}
type IntContact struct {
Type int `json:"contactType"`
}
Run Code Online (Sandbox Code Playgroud)
这完成了解组,但我无法设置ContactType取决于 的类型的变量json.RawMessage。如何对我的结构进行建模才能解决这个问题?