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 關注
- 151 瀏覽
添加回答
舉報