栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Go中解组可以是数组或字符串的字段?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Go中解组可以是数组或字符串的字段?

不幸的是,

json
软件包没有提供真正的自动解决方案。

但是您可以将依赖项解组为a

map[string]*json.RawMessage
而不是
map[string]string
json.RawMessage
只是一个
[]byte
,因此您可以根据第一个字节确定消息的类型。

例:

for _, value := range dependencies {    depVal := map[string]*json.RawMessage{}    _ = json.Unmarshal(*value, &depVal)    // check if the first character of the RawMessage is a bracket    if rune([]byte(*depVal["licenses"])[0]) == '[' {        var licenses []string        json.Unmarshal(*depVal["licenses"], &licenses)        fmt.Println(licenses)        // do something with the array    }    result = append(result, Dependency{        URL:     string(*depVal["repository"]),        License: string(*depVal["licenses"]),    })}

另一个解决方案是使用2个结构。一个以字符串形式包含依赖关系,另一个以数组形式包含依赖关系。然后,您可以尝试同时调用

json.Unmarshal
它们。例:

type Dependency struct {    Licenses string    // other fields}type DependencyWithArr struct {    Licenses []string    // other fields}// in your functionfor _, value := range dependencies {    type1 := Dependency{}    type2 := DependencyWithArr{}    err = json.Unmarshal(*value, &type1)    if err != nil {        err = json.Unmarshal(*value, &type2)        // use the array type    } else {        // use the single string type    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484227.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号