简体   繁体   English

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

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

Is it possible to create a struct with dynamic/arbitrary fields and values?是否可以创建具有动态/任意字段和值的结构?

My app will receive request with JSON body:我的应用程序将收到带有 JSON 正文的请求:

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

This will be unmarshalled to my model 'Request':这将被解组到我的模型“请求”:

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"`
}

I have to re-map model 'Request' to a new model 'Event' with arbitrary fields in "Values".我必须将模型“请求”重新映射到“值”中具有任意字段的新模型“事件”。 After marshalling new re- mapped model 'Event' I should get this JSON output that corresponds to the request:在编组新的重新映射模型“事件”后,我应该得到与请求相对应的 JSON 输出:

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

} }

Arbitrary values will be mapped from "RequestValues".任意值将从“RequestValues”映射。 Names of those fields should be the values of Request.RequestValues.Name and their values should be the values of Request.RequestValues.Value这些字段的名称应该是 Request.RequestValues.Name 的值,它们的值应该是 Request.RequestValues.Value 的值

Here is my 'Event' model:这是我的“事件”模型:

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

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

Firstly, here's a JSON-valid copy of your JSON:首先,这是您的 JSON 的 JSON 有效副本:

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

Start by creating a type Input struct{} to describe the JSON that you're looking to parse, and a type Output struct{} for the JSON that you're looking to generate, and write a little code to convert from one to the other.首先创建一个type Input struct{}来描述您要解析的 JSON,并创建一个type Output struct{}来描述您要生成的 JSON,然后编写一些代码以将其转换为其他。 You don't have to add all of the fields right away - you can start with just Event for example and add more until you've got them all.您不必立即添加所有字段 - 例如,您可以从Event开始,然后添加更多字段,直到您获得所有字段。

I've done this in https://play.golang.org/p/PvpKnFMrJjN to show you, but I would recommend having only a quick read of it before trying to recreate it yourself.我已在https://play.golang.org/p/PvpKnFMrJjN 中完成此操作以向您展示,但我建议您在尝试自己重新创建之前只快速阅读它。

A useful tool to convert JSON into Go structs is https://mholt.github.io/json-to-go/ but it will trip on RequestValue in your example which has several data types (and is therefore where we use interface{} ).将 JSON 转换为 Go 结构的有用工具是https://mholt.github.io/json-to-go/,但它会在您的示例中RequestValue该示例具有多种数据类型(因此我们使用interface{} )。

I thing that you can use map like this:我认为你可以像这样使用地图:

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)
}

You just need to validate somehow that the id it's in there, this if you need values in the same level.你只需要以某种方式验证它在那里的 id,如果你需要相同级别的值。

I hope this works for you.我希望这对你有用。

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

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