Golang 中將結構體轉換為Map 的函數
問題:
問題:如何
問題:如何
問題:如何
問題:func Map(object interface{}) map[string]interface{}
如何問在Golang 中有效地將結構轉換為映射,利用JSON 標籤作為鍵,其中可能嗎?
package main import ( "fmt" "github.com/fatih/structs" ) type Server struct { Name string `json:"name"` ID int32 `json:"id"` Enabled bool `json:"enabled"` } func main() { s := &Server{ Name: "gopher", ID: 123456, Enabled: true, } m := structs.Map(s) fmt.Println(m) // Output: {"name":"gopher", "id":123456, "enabled":true} }
答案:
用法:
func ConvertToMap(model interface{}) map[string]interface{} { // Get the reflect type and value of the model modelType := reflect.TypeOf(model) modelValue := reflect.ValueOf(model) if modelValue.Kind() == reflect.Ptr { modelValue = modelValue.Elem() } // Check if the model is a struct if modelType.Kind() != reflect.Struct { return nil } // Create a new map to store the key-value pairs ret := make(map[string]interface{}) // Iterate over the fields of the struct for i := 0; i < modelType.NumField(); i++ { // Get the field and its name field := modelType.Field(i) fieldName := field.Name // Check if the field has a JSON tag jsonTag := field.Tag.Get("json") if jsonTag != "" { fieldName = jsonTag } // Get the value of the field fieldValue := modelValue.Field(i) // Recursively convert nested structs switch fieldValue.Kind() { case reflect.Struct: ret[fieldName] = ConvertToMap(fieldValue.Interface()) default: ret[fieldName] = fieldValue.Interface() } } return ret }
以上是如何使用 JSON 標籤高效率地將 Go 結構體轉換為 Map?的詳細內容。更多資訊請關注PHP中文網其他相關文章!