From 7fc73f1e93efd6b559467fff3a5e7de86c4fba34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Tue, 11 Jun 2024 19:34:48 +0200 Subject: [PATCH] v0.0.470 Add GoextJsonMarshaller interface to call when marshalling json via gojson --- goextVersion.go | 4 ++-- gojson/encode.go | 7 +++++++ gojson/interfaces.go | 13 +++++++++++++ gojson/interfaces_test.go | 37 +++++++++++++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 gojson/interfaces.go create mode 100644 gojson/interfaces_test.go diff --git a/goextVersion.go b/goextVersion.go index b714638..7d6ec88 100644 --- a/goextVersion.go +++ b/goextVersion.go @@ -1,5 +1,5 @@ package goext -const GoextVersion = "0.0.469" +const GoextVersion = "0.0.470" -const GoextVersionTimestamp = "2024-06-11T12:10:49+0200" +const GoextVersionTimestamp = "2024-06-11T19:34:48+0200" diff --git a/gojson/encode.go b/gojson/encode.go index aca278f..903c03b 100644 --- a/gojson/encode.go +++ b/gojson/encode.go @@ -769,6 +769,13 @@ type structFields struct { } func (se structEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { + + if v.CanAddr() && v.Addr().Type().Implements(goextJsonMarshallerType) { + if gejm, ok := v.Addr().Interface().(GoextJsonMarshaller); ok { + gejm.PreGoJsonMarshal() + } + } + next := byte('{') FieldLoop: for i := range se.fields.list { diff --git a/gojson/interfaces.go b/gojson/interfaces.go new file mode 100644 index 0000000..5f0fe02 --- /dev/null +++ b/gojson/interfaces.go @@ -0,0 +1,13 @@ +package json + +import ( + "reflect" +) + +type GoextJsonMarshaller interface { + PreGoJsonMarshal() +} + +var ( + goextJsonMarshallerType = reflect.TypeOf((*GoextJsonMarshaller)(nil)).Elem() +) diff --git a/gojson/interfaces_test.go b/gojson/interfaces_test.go new file mode 100644 index 0000000..502afbe --- /dev/null +++ b/gojson/interfaces_test.go @@ -0,0 +1,37 @@ +package json + +import ( + "fmt" + "testing" +) + +type testStruct1 struct { + TS2 *testStruct2 `json:"ts2"` +} + +type testStruct2 struct { + A string `json:"a"` +} + +func (t *testStruct2) PreGoJsonMarshal() { + t.A = "Hello" +} + +func TestGoextJsonMarshaller(t *testing.T) { + t1 := testStruct1{TS2: &testStruct2{}} + + v, err := Marshal(t1) + if err != nil { + t.Fatal() + } + + fmt.Printf("%s\n", v) + + if string(v) != `{"ts2":{"a":"Hello"}}` { + t.Fatalf("PreGoJsonMarshal failed") + } + + if t1.TS2.A != "Hello" { + t.Fatalf("PreGoJsonMarshal failed") + } +}