【问题标题】:Go parse JSON with 2 nested types使用 2 种嵌套类型解析 JSON
【发布时间】:2025-12-26 02:05:17
【问题描述】:

我有 2 个对象,例如:

type appA struct {
  appType string
  frontend string
}

type appB struct {
  appType string
  backend string
}

我有一个JSON格式的配置文件,例如:

[
  {
    "appType" : "A",
    "frontend": "URL"
  },
  {
    "appType": "B",
    "backend": "SQL"
  }
]

根据this 的好主意 - 我创建了另一个结构:

type genericApp struct {
  appType string
}

所以现在我可以很好地解组 JSON 并知道 JSON 中的哪个对象是哪种应用程序。现在我的大问题是如何再次“编组和解组” - 我可以以某种方式引用已经解组的对象作为接口并将它们重新解组为不同的对象吗?

我唯一的其他解决方案是读取文件 N 次,每次读取每种结构类型,然后循环遍历 genericApp 数组并从相关数组中“收集”匹配的对象,但这听起来像是一种糟糕的做法。 ..

编辑 我已经使用json:...omitempty 表示法回答了这个问题,但我仍然有一个问题——如果两个单独的对象具有相同的字段名称和不同的类型怎么办?例如appType 可以是字符串还是数字?

【问题讨论】:

  • 首先,您应该导出您的结构字段以进行 json 解组,可能您没有注意,但是对于新手来说,看到正确的问题很重要。

标签: json go struct interface


【解决方案1】:

创建一个 config.json 文件并将该 json 放入其中,然后尝试 id :

type MyAppModel struct {
    AppType  string `json:"appType"`
    Frontend string `json:"frontend,omitempty"`
    Backend  string `json:"backend,omitempty"`
}

func(m *MyAppModel) GetJson()string{
    bytes,_:=json.Marshal(m)
    return string(bytes)
}

func (m MyAppModel) GetListJson(input []MyAppModel) string {
    bytes,_:=json.Marshal(input)
    return string(bytes)
}

func(m MyAppModel) ParseJson(inputJson string)[]MyAppModel{
    model:=[]MyAppModel{}
    err:=json.Unmarshal([]byte(inputJson),&model)
    if err!=nil{
        println(err.Error())
        return nil
    }
    return model
}

func inSomeMethodLikemain(){
    //reading from file
    bytes,err:=ioutil.ReadFile("config.json")
    if err!=nil{
        panic(err)
    }
    configs := MyAppModel{}.ParseJson(string(bytes))
    if configs==nil || len(configs)==0{
        panic(errors.New("no config data in config.json"))
    }
    println(configs[0].AppType)

    //writing to file

    jsonOfList:=MyAppModel{}.GetListJson(configs)
    err=ioutil.WriteFile("config.json",[]byte(jsonOfList),os.ModePerm))
    if err!=nil{
        panic(err.Error())
    }

}

【讨论】:

    【解决方案2】:

    发现你可以使用一些 go 语法来创建一个大的结构:

    type genericApp struct {
      appType string
      frontend string `json:"frontend, omitempty"`
      backend string `json:"backend, omitempty"`
    }
    

    但是,这有一些问题:

    1. 如果您有多种类型,它将创建一个巨大的结构(如果我有 20 个应用类型而不是 2 个,这将是 100 行长)
    2. 它没有给你两个独立的结构 - 你仍然需要稍后实现这种分离(switch-case,或类型转换等)

    【讨论】: