繁体   English   中英

如何使用动态/任意字段在 golang 中创建结构/模型

[英]how to create a struct/model in golang with dynamic/arbitrary fields

是否可以创建具有动态/任意字段和值的结构?

我的应用程序将收到带有 JSON 正文的请求:

{
"Details": {
  "Id": “123”,
 },
"Event": {
  "Event": "Event",
 },
“RequestValues”: [
  {
    “Name": "Name1",
    "Value": "Val1"
  },
  {
    "Name": "Name2",
    "Value": 2
  },
  {
    "Name": “Foo”,
    "Value": true
  }
    ]
  }

这将被解组到我的模型“请求”:

type Request struct {
    Details         Details          `json:"Details"`
    Event           Event            `json:"Event"`
    RequestValues []RequestValues    `json:"RequestValues"`
}

type Details struct {
    Id     string `json:"Id"`
}

type Event struct {
    Event      string `json:"Event"`
}

type RequestValues struct {
    Name  string `json:"Name"`
    Value string `json:"Value"`
}

我必须将模型“请求”重新映射到“值”中具有任意字段的新模型“事件”。 在编组新的重新映射模型“事件”后,我应该得到与请求相对应的 JSON 输出:

{
"Event": "Event"
"Values": {
  “Id": "123",      <= non arbitrary mapping from Request.Detail.Id
  "Name1": "Val1",  <= arbitrary 
  "Name2": 2,       <= arbitrary
  “Foo”: true       <= arbitrary
}

}

任意值将从“RequestValues”映射。 这些字段的名称应该是 Request.RequestValues.Name 的值,它们的值应该是 Request.RequestValues.Value 的值

这是我的“事件”模型:

type Event struct {
    Event             string `json:"Event"`
    Values            Values `json:"Values"`
}

type Values struct{
    Id      string  `json:"Id"`
}

首先,这是您的 JSON 的 JSON 有效副本:

{
    "Details": {
        "Id": "123"
    },
    "Event": {
        "Event": "Event"
    },
    "RequestValues": [
        {
            "RequestValueName": "Name1",
            "RequestValue": "Val1"
        },
        {
            "RequestValueName": "Name2",
            "RequestValue": 2
        },
        {
            "RequestValueName": "Foo",
            "RequestValue": true
        }
    ]
}

首先创建一个type Input struct{}来描述您要解析的 JSON,并创建一个type Output struct{}来描述您要生成的 JSON,然后编写一些代码以将其转换为其他。 您不必立即添加所有字段 - 例如,您可以从Event开始,然后添加更多字段,直到您获得所有字段。

我已在https://play.golang.org/p/PvpKnFMrJjN 中完成此操作以向您展示,但我建议您在尝试自己重新创建之前只快速阅读它。

将 JSON 转换为 Go 结构的有用工具是https://mholt.github.io/json-to-go/,但它会在您的示例中RequestValue该示例具有多种数据类型(因此我们使用interface{} )。

我认为你可以像这样使用地图:

package main

import (
    "fmt"
)

type Event struct {
    event  string
    values map[string]string
}

func main() {
    eventVar := Event{event: "event", values: map[string]string{}}
    eventVar.values["Id"] = "12345"
    eventVar.values["vale1"] = "value"
    fmt.Println(eventVar)
}

你只需要以某种方式验证它在那里的 id,如果你需要相同级别的值。

我希望这对你有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM