2 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
創(chuàng)建一個(gè) 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貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個(gè)贊
發(fā)現(xiàn)您可以使用一些 go 語(yǔ)法來(lái)創(chuàng)建一個(gè)大型結(jié)構(gòu):
type genericApp struct {
appType string
frontend string `json:"frontend, omitempty"`
backend string `json:"backend, omitempty"`
}
但是,這有一些問(wèn)題:
如果你有很多類型,它將創(chuàng)建一個(gè)巨大的結(jié)構(gòu)(如果我有 20 個(gè)應(yīng)用程序類型而不是 2 個(gè),這將是 100 行長(zhǎng))
它沒(méi)有給你兩個(gè)單獨(dú)的結(jié)構(gòu) - 你仍然需要稍后實(shí)現(xiàn)這種分離(開(kāi)關(guān)盒或類型轉(zhuǎn)換等)
- 2 回答
- 0 關(guān)注
- 148 瀏覽
添加回答
舉報(bào)