通过 JSON 映射重建 JSON 结构
时间:2024-03-22
浏览:320
作者:佚名
在反序列化 JSON 时,开发者尝试创建结构体来匹配 JSON 结构,但遇到了字段重复映射的问题。JSON 中两个对象都包含一个名为 "@odata.type" 的字段,而结构体中两个字段都被映射到了相同的 JSON 字段名称,导致 Go 编译器抛出错误。正确的解决方案是为每个 JSON 对象创建单独的结构体,并使用 "json:" 标签指定正确的 JSON 字段名称。
问题内容
我正在尝试反序列化 json,如下所示:
{
"pattern": {"@odata.type": "microsoft.graph.recurrencepattern"},
"range": {"@odata.type": "microsoft.graph.recurrencerange"}
}
为此,我创建了几个结构,其中第一个结构如下所示:
type mspatternedrecurrence struct {
pattern msrecurrencepattern `json:"@odata.type"`
range msrecurrencerange `json:"@odata.type"`
}
但是 go vet 会抛出这样的错误:
struct field range repeats json tag "@odata.type"
在这种情况下创建结构体的正确方法是什么?
类型 mspatternedrecurrence 结构 {
模式 msrecurrencepattern json:"@odata.type"
范围 msrecurrencerange json:"@odata.type"
}
type MSRecurrencePattern struct {
DayOfMonth int `json:"dayOfMonth"`
DayOfWeek []string `json:"daysOfWeek"`
FirstDayOfWeek string `json:"firstDayOfWeek"`
Index string `json:"index"`
Interval int `json:"interval"`
Month int `json:"month"`
Type string `json:"type"`
}
type MSRecurrenceRange struct {
EndDate string `json:"endDate"`
NumberOfOccurrences int `json:"numberOfOccurrences"`
RecurrenceTimeZone string `json:"recurrenceTimeZone"`
StartDate string `json:"startDate"`
Type string `json:"type"`
}解决方案
没有;该错误清楚地表明您正在尝试将两个结构字段映射到相同的 json 字段名称,但您不能这样做;此外,未给出用于这些字段的类型的定义,但考虑到 json 将它们都作为简单字符串,它们似乎不太可能是正确的。
您有两个字段:pattern 和 range。每个的值都是一个对象。这些对象每个都有一个名为 @odata.type 的字段。即:
type odata struct {
type string `json:"@odata.type"`
}
type mspatternedrecurrence struct {
pattern odata
range odata
}
您可能会发现 JSON-to-Go 工具很有用。对于此 json,它输出:
type AutoGenerated struct {
Pattern struct {
OdataType string `json:"@odata.type"`
} `json:"pattern"`
Range struct {
OdataType string `json:"@odata.type"`
} `json:"range"`
}理论要掌握,实操不能落!以上关于《通过 JSON 映射重建 JSON 结构》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
07.31
07.31
07.31
07.31
07.31
07.31
07.31
07.31
07.31
热门专题
