亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 2 種嵌套類型解析 JSON

使用 2 種嵌套類型解析 JSON

Go
慕哥6287543 2022-05-18 16:35:02
我有 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 中的哪個對象是哪種應用程序?,F在我的大問題是如何再次“編組和解組” - 我可以以某種方式引用已經解組的對象作為接口并將它們重新解組為不同的對象嗎?我唯一的其他解決方案是讀取文件 N 次,每次讀取每種結構類型,然后循環遍歷 genericApp 數組并從相關數組中“收集”匹配的對象,但這聽起來像是一種糟糕的做法......編輯 我已經使用符號回答了這個問題json:...omitempty,但我仍然有一個問題 - 如果兩個單獨的對象具有不同類型的相同字段名稱怎么辦?例如 appType 可以是字符串還是數字?
查看完整描述

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())

    }


}


查看完整回答
反對 回復 2022-05-18
?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

發現您可以使用一些 go 語法來創建一個大型結構:


type genericApp struct {

  appType string

  frontend string `json:"frontend, omitempty"`

  backend string `json:"backend, omitempty"`

}

但是,這有一些問題:


如果你有很多類型,它將創建一個巨大的結構(如果我有 20 個應用程序類型而不是 2 個,這將是 100 行長)

它沒有給你兩個單獨的結構 - 你仍然需要稍后實現這種分離(開關盒或類型轉換等)


查看完整回答
反對 回復 2022-05-18
  • 2 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號