diff --git a/goextVersion.go b/goextVersion.go index 44071ba..9e81fb7 100644 --- a/goextVersion.go +++ b/goextVersion.go @@ -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" diff --git a/reflectext/convertToMap.go b/reflectext/convertToMap.go index f8721b4..b46c513 100644 --- a/reflectext/convertToMap.go +++ b/reflectext/convertToMap.go @@ -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) } }