解构2个不同的结构 [英] Unmarshal 2 different structs in a slice

查看:89
本文介绍了解构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
]


推荐答案

使用at wo步骤处理unmarshaling。首先,解组任意JSON的列表,然后将该列表的第一个和第二个元素解组到它们各自的类型中。

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

您可以使用名为UnmarshalJSON的方法实现该逻辑,从而实现json.Unmarshaller接口。这会给你你想要的复合类型:

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

type ParallelData struct {
    UrlData  UrlData
    FormData FormData
}

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天全站免登陆