去解析2种嵌套类型的JSON

时间:2020-03-03 09:22:03

标签: json go struct interface

我有2个对象,例如:

type appA struct {
  appType string
  frontend string
}

type appB struct {
  appType string
  backend string
}

我有一个JSON格式的配置文件,例如:

[
  {
    "appType" : "A",
    "frontend": "URL"
  },
  {
    "appType": "B",
    "backend": "SQL"
  }
]

根据this个好主意-我创建了另一个结构:

type genericApp struct {
  appType string
}

因此,现在我可以很好地解组JSON,并知道JSON中的哪个对象是哪种应用程序。现在我的大问题是如何再次“编组和解组”-我可以以某种方式将已经解组的对象引用为接口,然后将它们重新解组为其他对象吗?

我唯一的其他解决方案是对每种结构类型分别读取N次文件,然后遍历genericApp数组并从相关数组中“收集”匹配的对象,但这听起来像是一种糟糕的做法。 ..

编辑 我已经使用json:...omitempty表示法回答了问题,但是仍然有一个问题-如果两个单独的对象具有不同类型的相同字段名怎么办?例如appType可以是字符串还是数字?

2 个答案:

答案 0 :(得分:2)

创建一个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())
    }

}

答案 1 :(得分:-1)

发现您可以使用一些go语法来创建大型结构:

type genericApp struct {
  appType string
  frontend string `json:"frontend, omitempty"`
  backend string `json:"backend, omitempty"`
}

但是,这有一些问题:

  1. 如果您有很多类型,它将创建一个巨大的结构(如果我有20种应用程序类型,而不是2种,那将是100行长)
  2. 它没有给您两个单独的结构-您仍然需要稍后实现这种分离(切换大小写或类型转换等)