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

在Go中解组不一致的JSON

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

在Go中解组不一致的JSON

如果实现json.Unmarshaler,则可以定义一个将每种项目类型解析为相关结构的结构。

例:

// Dynamic represents an item of any type.type Dynamic struct {    Value interface{}}// UnmarshalJSON is called by the json package when we ask it to// parse something into Dynamic.func (d *Dynamic) UnmarshalJSON(data []byte) error {    // Parse only the "type" field first.    var meta struct {        Type string    }    if err := json.Unmarshal(data, &meta); err != nil {        return err    }    // Determine which struct to unmarshal into according to "type".    switch meta.Type {    case "product":        d.Value = &Product{}    case "post":        d.Value = &Post{}    default:        return fmt.Errorf("%q is an invalid item type", meta.Type)    }    return json.Unmarshal(data, d.Value)}// Product and Post are structs representing two different item types.type Product struct {    Name  string    Price int}type Post struct {    Title   string    Content string}

用法:

func main() {    // Parse a JSON item into Dynamic.    input := `{        "type": "product",        "name": "iPhone",        "price": 1000    }`    var dynamic Dynamic    if err := json.Unmarshal([]byte(input), &dynamic); err != nil {        log.Fatal(err)    }    // Type switch on dynamic.Value to get the parsed struct.    // See https://tour.golang.org/methods/16    switch dynamic.Value.(type) {    case *Product:        log.Println("got a product:", dynamic.Value)    case *Post:        log.Println("got a product:", dynamic.Value)    }}

输出:

2009/11/10 23:00:00得到了一个产品:&{iPhone 1000}

在Go Playground中尝试一下。


提示:如果您有动态对象列表,只需将其解析为

Dynamic

var items []Dynamicjson.Unmarshal(`[{...}, {...}]`, &items)

输出示例:

[&{iPhone 1000}&{A Good Post Lorem ipsum …}]



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

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

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