小编Rup*_*gar的帖子

使用 json.RawMessage 将 json 解组为结构

我需要解组 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。如何对我的结构进行建模才能解决这个问题?

json go unmarshalling

5
推荐指数
1
解决办法
7140
查看次数

标签 统计

go ×1

json ×1

unmarshalling ×1