From 0d6d72b07ee89e279a6944d6af079df26632a562 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 19 Nov 2024 15:39:37 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0Map=20MarshalJSON=20=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- map.go | 20 +++++++++++++++++--- map_test.go | 17 +++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/map.go b/map.go index 46145c4..16ae07c 100644 --- a/map.go +++ b/map.go @@ -9,6 +9,7 @@ package wrapper import ( "errors" + "git.zhangdeman.cn/zhangdeman/serialize" "reflect" "sync" ) @@ -148,9 +149,9 @@ func (m *Map) GetDefault(field string, defaultValue any, allowNil bool) any { // Author : go_developer@163.com<白茶清欢> // // Date : 19:39 2024/11/6 -func (m *Map) Value() Map { - if nil == m { - return map[string]any{} +func (m *Map) Value() map[string]any { + if m.IsNil() { + return nil } return *m } @@ -213,3 +214,16 @@ func (m *Map) FilterDefault(fieldMap map[string]any, allowNil bool) map[string]a } return res } + +// MarshalJSON Map序列化 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 15:35 2024/11/19 +func (m *Map) MarshalJSON() ([]byte, error) { + mapData := m.Value() + if nil == mapData { + return nil, nil + } + return serialize.JSON.MarshalForByte(mapData) +} diff --git a/map_test.go b/map_test.go index e57cc26..58652ee 100644 --- a/map_test.go +++ b/map_test.go @@ -28,3 +28,20 @@ func TestMap_IsNil(t *testing.T) { fmt.Println(m.Set("a", 1)) fmt.Println(m.IsNil(), m1.IsNil()) } + +func TestMap_IsMasher(t *testing.T) { + var ( + m Map + m1 = Map(map[string]any{ + "a": 1, + "b": m, + "c": Map(map[string]any{ + "name": "de", + }), + }) + ) + d, err := m.MarshalJSON() + fmt.Println(string(d), err) + d, err = m1.MarshalJSON() + fmt.Println(string(d), err) +}