Go小工具系列——类型转换

struct to map

// struct to map
func Struct2Map(obj interface{}) map[string]interface{} {
    var ret map[string]interface{}
    jsonStr, _ := json.Marshal(obj)
    err := json.Unmarshal(jsonStr, &ret)
    if err != nil {
        panic("struct to map error")
    }
    return ret
}

map to xml

import (
    "github.com/flosch/pongo2/v4"
)

// map to xml
func Map2xml(inputMap map[string]interface{}, droolsName string) string {
    for k, v := range inputMap {
        switch v.(type) {
        case float64:
            inputMap[k] = strconv.FormatFloat(v.(float64), 'f', -1, 64)
        default:
            inputMap[k] = fmt.Sprintf("%v", v)
        }
    }

    tpl, _ := pongo2.FromFile(droolsPath)
    out, _ := tpl.Execute(inputMap)

    return out
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!