From 8446b2da22e1fb06c903b9af875900f27b989d0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Mon, 8 Apr 2024 16:32:34 +0200 Subject: [PATCH] v0.0.428 --- goextVersion.go | 4 ++-- reflectext/convertToMap.go | 12 +++++++++- reflectext/convertToMap_test.go | 42 +++++++++++++++++++++++++++++++++ reflectext/mapAccess_test.go | 6 ----- 4 files changed, 55 insertions(+), 9 deletions(-) create mode 100644 reflectext/convertToMap_test.go diff --git a/goextVersion.go b/goextVersion.go index 741abfc..a36b771 100644 --- a/goextVersion.go +++ b/goextVersion.go @@ -1,5 +1,5 @@ package goext -const GoextVersion = "0.0.427" +const GoextVersion = "0.0.428" -const GoextVersionTimestamp = "2024-04-07T15:10:21+0200" +const GoextVersionTimestamp = "2024-04-08T16:32:34+0200" diff --git a/reflectext/convertToMap.go b/reflectext/convertToMap.go index b46c513..ca75a0c 100644 --- a/reflectext/convertToMap.go +++ b/reflectext/convertToMap.go @@ -2,6 +2,7 @@ package reflectext import ( "encoding/json" + "gogs.mikescher.com/BlackForestBytes/goext/langext" "reflect" ) @@ -14,7 +15,16 @@ func ConvertStructToMap(v any, opts ...ConvertStructToMapOpt) any { if len(opts) > 0 { opt = opts[0] } - return reflectToMap(reflect.ValueOf(v), opt) + + res := reflectToMap(reflect.ValueOf(v), opt) + + if v, ok := res.(map[string]any); ok { + return v + } else if langext.IsNil(res) { + return nil + } else { + panic("not an object") + } } func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) any { diff --git a/reflectext/convertToMap_test.go b/reflectext/convertToMap_test.go new file mode 100644 index 0000000..2ea2641 --- /dev/null +++ b/reflectext/convertToMap_test.go @@ -0,0 +1,42 @@ +package reflectext + +import ( + "fmt" + "gogs.mikescher.com/BlackForestBytes/goext/langext" + "testing" + "time" +) + +func TestConvertStructToMap(t *testing.T) { + + type tst struct { + FieldA int + FieldB string + FieldC time.Time + FieldD []float64 + FieldE1 *int + FieldE2 **int + FieldE3 *int + FieldE4 **int + FieldE5 *int + FieldE6 **int + } + + value := tst{ + FieldA: 123, + FieldB: "hello", + FieldC: time.Date(2020, 05, 12, 8, 30, 0, 0, time.UTC), + FieldD: []float64{1, 2, 3, 4, 5, 6, 7}, + FieldE1: nil, + FieldE2: nil, + FieldE3: langext.Ptr(12), + FieldE4: langext.DblPtr(12), + FieldE5: nil, + FieldE6: langext.DblPtrNil[int](), + } + + valueOut := ConvertStructToMap(value, ConvertStructToMapOpt{KeepJsonMarshalTypes: true}) + + fmt.Printf("%+v\n", valueOut) + +} diff --git a/reflectext/mapAccess_test.go b/reflectext/mapAccess_test.go index 4c6a687..589c50a 100644 --- a/reflectext/mapAccess_test.go +++ b/reflectext/mapAccess_test.go @@ -47,9 +47,3 @@ func TestGetMapField(t *testing.T) { tst.AssertEqual(t, fmt.Sprint(GetMapField[PseudoInt](maany2, "Test")), "12 true") tst.AssertEqual(t, fmt.Sprint(GetMapField[PseudoInt](maany2, "Test2")), "0 false") } - -func main2() { -} - -func main() { -}