在切片中解组 2 个不同的结构 [英] Unmarshal 2 different structs in a slice

查看:37
本文介绍了在切片中解组 2 个不同的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我输入的 json 数据是这样的(无法更改,来自外部资源):

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
]

推荐答案

使用两步过程进行解组.首先,解组任意 JSON 的列表,然后将该列表的第一个和第二个元素解组为各自的类型.

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.

您可以在名为 UnmarshalJSON 的方法中实现该逻辑,从而实现 json.Unmarshaler 接口.这将为您提供您正在寻找的化合物类型:

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
}

在操场上试试:https://play.golang.org/p/QMn_rbJj-P-

这篇关于在切片中解组 2 个不同的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆