PHP试题网_中国最大的免费网络PHP试题测试平台,PHP试卷调查,PHP试卷模板、PHP考试测验
公告: PHP试题网于2022.06.21变更为少儿编程学院

一、通过struct转json,json转成map

func StructToMapViaJson() {
    m := make(map[string]interface{})
    t := time.Now()
    person := Persion{
        Id:       98439,
        Name:     "zhaondifnei",
        Address:  "大沙地",
        Email:    "dashdisnin@126.com",
        School:   "广州第十五中学",
        City:     "zhongguoguanzhou",
        Company:  "sndifneinsifnienisn",
        Age:      23,
        Sex:      "F",
        Proviece: "jianxi",
        Com:      "广州兰博基尼",
        PostTo:   "蓝鲸XXXXXXXX",
        Buys:     "shensinfienisnfieni",
        Hos:      "zhonsndifneisnidnfie",
    }
    j, _ := json.Marshal(person)
    json.Unmarshal(j, &m)
    fmt.Println(m)
    fmt.Printf("duration:%d", time.Now().Sub(t))
}

二、通过反射形式生成map

func StructToMapViaReflect() {
    m := make(map[string]interface{})
    t := time.Now()
    person := Persion{
        Id:       98439,
        Name:     "zhaondifnei",
        Address:  "大沙地",
        Email:    "dashdisnin@126.com",
        School:   "广州第十五中学",
        City:     "zhongguoguanzhou",
        Company:  "sndifneinsifnienisn",
        Age:      23,
        Sex:      "F",
        Proviece: "jianxi",
        Com:      "广州兰博基尼",
        PostTo:   "蓝鲸XXXXXXXX",
        Buys:     "shensinfienisnfieni",
        Hos:      "zhonsndifneisnidnfie",
    }
    elem := reflect.ValueOf(&person).Elem()
    relType := elem.Type()
    for i := 0; i < relType.NumField(); i++ {
        m[relType.Field(i).Name] = elem.Field(i).Interface()
    }
    fmt.Println(m)
    fmt.Printf("duration:%d", time.Now().Sub(t))
}




作者:OK兄 浏览次数:20