动态结构定义

我有一个用例,我将一些 json 文件转换为 Go 结构。我有以下文档结构


{

    

    "contentVersion": "1.0.0.0",


    "paths" : [

      {

        "ParameterReference": "someValue",

      },

      {

        "ParameterReference": "someOtherValue",

      }

    ],

    "parameters": {

        "label": { "value": "label" },

        "domainName": { "value": "domain" },

        "servicePackageLink": { "value": "bin\\test.cspkg" },

        "pfxContent": { "value": "SampleCert.Content" },

        "sampleCertThumbprint": {"value": "SampleCert.Thumbprint"},

        "anotherSampleCertContent":{ "value" : "AnotherSampleCert.Content" },

        "anotherSampleCertThumbprint": {"value": "AnotherSampleCert.Thumbprint"}

    },

    "secrets" :[

      {

        "TargetReference":"SERviceConfiGURatiONLiNK",

        "Replacements":

        {

          "__Secret_Sample__" :

          {

            "SecretId":"secretID",

            "EncryptWith" :"encryptWithValue"

          },

          "__Another_Secret_Sample__" :

          {

            "SecretId":"anotherSecretValue",

            "EncryptWith" :"anotherEncryptWithValue"

          },

          "__Storage_ConnectionString__" : "someConnectionString"

        },

      },

      {

        "TargetReference":"None",

        "Certificates":[

          {

            "Name":"AnotherSampleCert",

            "ContentReference" : "contentReference"

          }

        ]

      }

    ]

}

  

我面临的问题是 json 没有固定的模式,例如。


如果您检查parameters对象,特别是名称为 的条目sampleCertSchema,在我的用例中,用户可以提供从 0 到 N 的任意数量的此类____CertSchemas值。因此,参数字段也可以如下

"parameters": {

        "label": { "value": "label" },

        "domainName": { "value": "domain" },

        "servicePackageLink": { "value": "bin\\test.cspkg" },

        "pfxContent": { "value": "SampleCert.Content" }

    },

这将打印一个空结构。我的问题是,我应该如何在 Go 中定义一个结构,以便它能够加载一个带有非预定义条目的 json。使用 java/C# 我可以使用Object该类并创建一个文档,但我无法理解使用 Go 来执行此操作。


潇湘沐
浏览 147回答 2
2回答

千万里不及你

go 中的等价物是 interface{},即空接口。例如,查看这个答案:Unmarshaling Into an Interface{} and Then Performing Type Assertion一旦您知道要搜索的术语,您应该能够在需要时搜索更详细的内容。

互换的青春

 https://play.golang.org/p/SOsKGCZtlxk
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go