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

问题描述

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

我的应用将收到带有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"`
}

我必须使用“值”中的任意字段将模型“请求”重新映射到新模型“事件”。在编组新的重新映射的模型'Event'之后,我应该获得与请求相对应的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"`
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)