dtwy2858 2018-02-09 02:40
浏览 13
已采纳

在切片中解组2个不同的结构

My input json data is this (cannot be changed, from an external resource):

[{
   "Url": "test.url",
   "Name": "testname"
},{ 
   "FormName": "Test - 2018",
   "FormNumber": 43,
   "FormSlug": "test-2018"
}]

I have two structs that will always match the data within the array:

type UrlData struct{
  "Url"  string `json:Url` 
  "Name" string `json:Name` 
}

type FormData struct{
  "FormName"  string `json:FormName` 
  "FormNumber" string `json:FormNumber` 
  "FormSlug" string `json:FormSlug`
}

Obviously the code below will not work, but is it possible at the top level (or otherwise) to declare something like this:

type ParallelData [
 urlData UrlData
 formData FormData
]
  • 写回答

3条回答 默认 最新

  • dtdfj08626 2018-02-09 07:59
    关注

    Use a two step process for unmarshaling. First, unmarshal a list of arbitrary JSON, then unmarshal the first and second element of that list into their respective types.

    You can implement that logic in a method called UnmarshalJSON, thus implementing the json.Unmarshaler interface. This will give you the compound type you are looking for:

    type ParallelData struct {
        UrlData  UrlData
        FormData FormData
    }
    
    // UnmarshalJSON implements json.Unmarshaler.
    func (p *ParallelData) UnmarshalJSON(b []byte) error {
        var records []json.RawMessage
        if err := json.Unmarshal(b, &records); err != nil {
            return err
        }
    
        if len(records) < 2 {
            return errors.New("Short JSON array")
        }
    
        if err := json.Unmarshal(records[0], &p.UrlData); err != nil {
            return err
        }
    
        if err := json.Unmarshal(records[1], &p.FormData); err != nil {
            return err
        }
    
        return nil
    }
    

    Try it on the playground: https://play.golang.org/p/QMn_rbJj-P-

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)