v0.0.416
Some checks failed
Build Docker and Deploy / Run goext test-suite (push) Failing after 1m43s
Some checks failed
Build Docker and Deploy / Run goext test-suite (push) Failing after 1m43s
This commit is contained in:
parent
dcd106c1cd
commit
14f39a9162
@ -1,5 +1,5 @@
|
||||
package goext
|
||||
|
||||
const GoextVersion = "0.0.415"
|
||||
const GoextVersion = "0.0.416"
|
||||
|
||||
const GoextVersionTimestamp = "2024-03-18T10:42:00+0100"
|
||||
const GoextVersionTimestamp = "2024-03-18T11:19:01+0100"
|
||||
|
@ -1,19 +1,30 @@
|
||||
package reflectext
|
||||
|
||||
import "reflect"
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func ConvertStructToMap(v any) any {
|
||||
return reflectToMap(reflect.ValueOf(v))
|
||||
type ConvertStructToMapOpt struct {
|
||||
KeepJsonMarshalTypes bool
|
||||
}
|
||||
|
||||
func reflectToMap(fv reflect.Value) any {
|
||||
func ConvertStructToMap(v any, opts ...ConvertStructToMapOpt) any {
|
||||
opt := ConvertStructToMapOpt{}
|
||||
if len(opts) > 0 {
|
||||
opt = opts[0]
|
||||
}
|
||||
return reflectToMap(reflect.ValueOf(v), opt)
|
||||
}
|
||||
|
||||
func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) any {
|
||||
|
||||
if fv.Kind() == reflect.Ptr {
|
||||
|
||||
if fv.IsNil() {
|
||||
return nil
|
||||
} else {
|
||||
return reflectToMap(fv.Elem())
|
||||
return reflectToMap(fv.Elem(), opt)
|
||||
}
|
||||
|
||||
}
|
||||
@ -30,7 +41,7 @@ func reflectToMap(fv reflect.Value) any {
|
||||
arrlen := fv.Len()
|
||||
arr := make([]any, arrlen)
|
||||
for i := 0; i < arrlen; i++ {
|
||||
arr[i] = reflectToMap(fv.Index(i))
|
||||
arr[i] = reflectToMap(fv.Index(i), opt)
|
||||
}
|
||||
return arr
|
||||
|
||||
@ -41,7 +52,7 @@ func reflectToMap(fv reflect.Value) any {
|
||||
arrlen := fv.Len()
|
||||
arr := make([]any, arrlen)
|
||||
for i := 0; i < arrlen; i++ {
|
||||
arr[i] = reflectToMap(fv.Index(i))
|
||||
arr[i] = reflectToMap(fv.Index(i), opt)
|
||||
}
|
||||
return arr
|
||||
|
||||
@ -56,11 +67,15 @@ func reflectToMap(fv reflect.Value) any {
|
||||
|
||||
if fv.Kind() == reflect.Struct {
|
||||
|
||||
if opt.KeepJsonMarshalTypes && fv.Type().Implements(reflect.TypeFor[json.Marshaler]()) {
|
||||
return fv.Interface()
|
||||
}
|
||||
|
||||
res := make(map[string]any)
|
||||
|
||||
for i := 0; i < fv.NumField(); i++ {
|
||||
if fv.Type().Field(i).IsExported() {
|
||||
res[fv.Type().Field(i).Name] = reflectToMap(fv.Field(i))
|
||||
res[fv.Type().Field(i).Name] = reflectToMap(fv.Field(i), opt)
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user