Browse Source

增加序列化过程的回调函数

feature_wq
Sydonian 9 months ago
parent
commit
e0f6c83596
3 changed files with 44 additions and 0 deletions
  1. +29
    -0
      utils/serder/serder_test.go
  2. +4
    -0
      utils/serder/types/types.go
  3. +11
    -0
      utils/serder/union_handler.go

+ 29
- 0
utils/serder/serder_test.go View File

@@ -665,3 +665,32 @@ func Test_ObjectToJSON3(t *testing.T) {
// So(ret, ShouldResemble, val)
})
}

type BaseCallback interface{}
type StCallback struct {
Metadata `union:"StCallback"`
Type string
Value string
}

func (st *StCallback) OnUnionSerializing() {
st.Value = "called"
st.Type = "StCallback"
}

func Test_ObjectToJSONEx4(t *testing.T) {
Convey("序列化Callback", t, func() {
union := types.NewTypeUnion[BaseCallback](&StCallback{})
UseTypeUnionInternallyTagged(&union, "Type")

val := []BaseCallback{&StCallback{}}
data, err := ObjectToJSONEx(val)
So(err, ShouldBeNil)

ret, err := JSONToObjectEx[[]BaseCallback](data)
So(err, ShouldBeNil)

So(len(ret), ShouldEqual, 1)
So(ret[0].(*StCallback).Value, ShouldEqual, "called")
})
}

+ 4
- 0
utils/serder/types/types.go View File

@@ -1,3 +1,7 @@
package types

type Metadata struct{}

type OnUnionSerializing interface {
OnUnionSerializing()
}

+ 11
- 0
utils/serder/union_handler.go View File

@@ -8,6 +8,7 @@ import (
jsoniter "github.com/json-iterator/go"
"github.com/modern-go/reflect2"
"gitlink.org.cn/cloudream/common/pkgs/types"
sertypes "gitlink.org.cn/cloudream/common/utils/serder/types"

ref2 "gitlink.org.cn/cloudream/common/utils/reflect2"
)
@@ -211,6 +212,12 @@ func (e *InternallyTaggedEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.St
val = reflect2.IFaceToEFace(ptr)
}

if val != nil {
if on, ok := val.(sertypes.OnUnionSerializing); ok {
on.OnUnionSerializing()
}
}

// 可以考虑检查一下Type字段有没有赋值,没有赋值则将其赋值为union Tag指定的值
stream.WriteVal(val)
}
@@ -292,6 +299,10 @@ func (e *ExternallyTaggedEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.St
return
}

if on, ok := val.(sertypes.OnUnionSerializing); ok {
on.OnUnionSerializing()
}

stream.WriteObjectStart()
valType := ref2.TypeOfValue(val)
if !e.union.Union.Include(valType) {


Loading…
Cancel
Save