map转struct

5年以前  |  阅读数:538 次  |  编程语言:Golang 

有时候我们需要分多步解析JSON,比如一个常见的场景就是:JSON串中有一个字段表类型,后面的数据根据类型有不同的结构体与之对应。本示例试着解决这个问题。

需要安装一个第三方库mapstructure

在命令行中运行: go get github.com/goinggo/mapstructure

例子:

func MapToStructDemo(){
        mapInstance := make(map[string]interface{})
        mapInstance["Name"] = "jqw"
        mapInstance["Age"] = 18

        var people People
        err := mapstructure.Decode(mapInstance, &people)
        if err != nil {
                fmt.Println(err)
        }
        fmt.Println(people)
}

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8