使用 2 种嵌套类型解析 JSON

我有 2 个对象,例如:


type appA struct {

  appType string

  frontend string

}


type appB struct {

  appType string

  backend string

}

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


[

  {

    "appType" : "A",

    "frontend": "URL"

  },

  {

    "appType": "B",

    "backend": "SQL"

  }

]

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


type genericApp struct {

  appType string

}

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


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


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


慕哥6287543
浏览 158回答 2
2回答

动漫人物

创建一个 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())    }}

一只萌萌小番薯

发现您可以使用一些 go 语法来创建一个大型结构:type genericApp struct {  appType string  frontend string `json:"frontend, omitempty"`  backend string `json:"backend, omitempty"`}但是,这有一些问题:如果你有很多类型,它将创建一个巨大的结构(如果我有 20 个应用程序类型而不是 2 个,这将是 100 行长)它没有给你两个单独的结构 - 你仍然需要稍后实现这种分离(开关盒或类型转换等)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go