2 回答

TA贡献1815条经验 获得超10个赞
创建一个 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())
}
}

TA贡献1795条经验 获得超7个赞
发现您可以使用一些 go 语法来创建一个大型结构:
type genericApp struct {
appType string
frontend string `json:"frontend, omitempty"`
backend string `json:"backend, omitempty"`
}
但是,这有一些问题:
如果你有很多类型,它将创建一个巨大的结构(如果我有 20 个应用程序类型而不是 2 个,这将是 100 行长)
它没有给你两个单独的结构 - 你仍然需要稍后实现这种分离(开关盒或类型转换等)
- 2 回答
- 0 关注
- 157 浏览
添加回答
举报