增加Map MarshalJSON 方法

This commit is contained in:
白茶清欢 2024-11-19 15:39:37 +08:00
parent db7bf0817e
commit 0d6d72b07e
2 changed files with 34 additions and 3 deletions

20
map.go
View File

@ -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)
}

View File

@ -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)
}