为了账号安全,请及时绑定邮箱和手机立即绑定

使用 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 中的哪个对象是哪种应用程序。现在我的大问题是如何再次“编组和解组” - 我可以以某种方式引用已经解组的对象作为接口并将它们重新解组为不同的对象吗?我唯一的其他解决方案是读取文件 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 关注
  • 157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号