duanjigua5753 2019-05-30 21:36
浏览 87
已采纳

使用重复的JSON映射将JSON反序列化为结构

I am trying to deserialize JSON which looks like this:

{
  "pattern": {"@odata.type": "microsoft.graph.recurrencePattern"},
  "range": {"@odata.type": "microsoft.graph.recurrenceRange"}
}

For this I created several structs where the first one looks like this:

type MSPatternedRecurrence struct {
    Pattern MSRecurrencePattern `json:"@odata.type"`
    Range   MSRecurrenceRange   `json:"@odata.type"`
}

However go vet throws an error like this:

struct field Range repeats json tag "@odata.type"

What is the right way to create a struct in this situation?

type MSPatternedRecurrence struct { Pattern MSRecurrencePattern json:"@odata.type" Range 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"`
}
  • 写回答

1条回答 默认 最新

  • douyue7408 2019-05-30 21:39
    关注

    No; the error clearly states you're trying to map two struct fields to the same JSON field name, which you cannot do; also, the definitions for the types used for those fields aren't given, but it seems unlikely they're correct given that the JSON has them both as simple strings.

    You have two fields, pattern and range. Each's value is an object. Those objects each have a field named @odata.type. I.e.:

    type Odata struct {
        Type string `json:"@odata.type"`
    }
    
    type MSPatternedRecurrence struct {
        Pattern Odata
        Range   Odata
    }
    

    You might find the JSON-to-Go tool useful. For this JSON, it outputs:

    type AutoGenerated struct {
        Pattern struct {
            OdataType string `json:"@odata.type"`
        } `json:"pattern"`
        Range struct {
            OdataType string `json:"@odata.type"`
        } `json:"range"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan