如何在golang中为不同用户定义对象的数组创建用户定义结构

how to create user defined struct for array of different user defined object in golang

我正在尝试解析 golang 中的 json 对象。

下面是 json 结构:

{
    "properties": {
        "alertType": "VM_EICAR",
        "resourceIdentifiers": [{
                "azureResourceId": "/Microsoft.Compute/virtualMachines/vm1",
                "type": "AzureResource"
            },
            {
                "workspaceId": "f419f624-acad-4d89-b86d-f62fa387f019",
                "workspaceSubscriptionId": "20ff7fc3-e762-44dd-bd96-b71116dcdc23",
                "workspaceResourceGroup": "myRg1",
                "agentId": "75724a01-f021-4aa8-9ec2-329792373e6e",
                "type": "LogAnalytics"
            }
        ],

        "vendorName": "Microsoft",
        "status": "New"

    }
}

我有以下用户定义的类型。

type AzureResourceIdentifier struct {
    AzureResourceId                 string                      `json:"azureResourceId"`
    Type                            string                      `json:"type"`           
}

type LogAnalyticsIdentifier struct{
    AgentId                     string          `json:"agentId"`
    Type                        string          `json:"type"`
    WorkspaceId                 string          `json:"workspaceId"`
    WorkspaceResourceGroup      string          `json:"workspaceResourceGroup"`
    WorkspaceSubscriptionId     string          `json:"workspaceSubscriptionId"`
}

我有一个顶级用户定义类型 properties,如下所示。 它有 resourceIdentifiers 作为两个其他用户定义类型(上面定义)的数组,

如何在属性中定义 resourceIdentifiers 的类型?

type Properties struct{
          alertType               string                        
          resourceIdentifiers               ???                         `
          vendorName                  string                        `
          status              string                           
}

注意:我有一个现有的连接器,我们被配置为输入解析的结构json,我们不能覆盖或添加任何函数。

这里有几个选项。

  1. []map[string]interface{}

使用映射将允许解析数组中的任何 JSON 对象,但您必须在事后安全地提取信息,这会给您带来负担。

  1. []interface{}

每个都将是引擎盖下的地图,除非 non-JSON 对象元素也可以在 JSON 数组中。在你的情况下,没有理由在 map[string]interface{} 上使用它。

  1. 涵盖所有可能字段的新结构类型的一部分:[]ResourceIdentifier
type ResourceIdentifier struct {
    AzureResourceId             string `json:"azureResourceId"`
    AgentId                     string `json:"agentId"`
    WorkspaceId                 string `json:"workspaceId"`
    WorkspaceResourceGroup      string `json:"workspaceResourceGroup"`
    WorkspaceSubscriptionId     string `json:"workspaceSubscriptionId"`
    
    Type                        string `json:"type"`
}

这可能是最懒惰的解决方案。它允许你快速到达你想去的地方,代价是浪费一些内存和创建一个非 self-explanatory 数据设计,如果稍后尝试再次序列化它可能会造成混乱。

  1. 新的结构类型 + 自定义解组实现。
type ResourceIdentifiers struct {
    AzureResourceIdentifiers []AzureResourceIdentifier
    LogAnalyticsIdentifiers []LogAnalyticsIdentifier
}

实施json.Unmarshaler来决定构建哪种类型的结构以及将其放置在哪个切片中。