珍惜时间,勤奋学习!今天给大家带来《使用 2 个嵌套类型解析 JSON》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!
我有 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 可以是字符串还是数字?
解决方案
创建一个 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 个嵌套类型解析 JSON》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
