From 9a3d2c62e3215f596001d0228d10d0703f79cc79 Mon Sep 17 00:00:00 2001 From: Victor Starodub Date: Tue, 29 Mar 2016 16:04:34 +0300 Subject: [PATCH] Standard marshallers for easyjson.RawMessage. --- raw.go | 16 ++++++++++++++++ tests/basic_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/raw.go b/raw.go index 49b4425..737c73a 100644 --- a/raw.go +++ b/raw.go @@ -23,6 +23,22 @@ func (v *RawMessage) UnmarshalEasyJSON(l *jlexer.Lexer) { *v = RawMessage(l.Raw()) } +// UnmarshalJSON implements encoding/json.Unmarshaler interface. +func (v *RawMessage) UnmarshalJSON(data []byte) error { + *v = data + return nil +} + +var nullBytes = []byte("null") + +// MarshalJSON implements encoding/json.Marshaler interface. +func (v RawMessage) MarshalJSON() ([]byte, error) { + if len(v) == 0 { + return nullBytes, nil + } + return v, nil +} + // IsDefined is required for integration with omitempty easyjson logic. func (v *RawMessage) IsDefined() bool { return len(*v) > 0 diff --git a/tests/basic_test.go b/tests/basic_test.go index 48ec043..3c1017c 100644 --- a/tests/basic_test.go +++ b/tests/basic_test.go @@ -5,6 +5,7 @@ import ( "testing" "encoding/json" + "github.com/mailru/easyjson" ) type testType interface { @@ -56,3 +57,33 @@ func TestUnmarshal(t *testing.T) { } } } + +func TestRawMessageSTD(t *testing.T) { + type T struct { + F easyjson.RawMessage + Fnil easyjson.RawMessage + } + + val := T{F: easyjson.RawMessage([]byte(`"test"`))} + str := `{"F":"test","Fnil":null}` + + data, err := json.Marshal(val) + if err != nil { + t.Errorf("json.Marshal() error: %v", err) + } + got := string(data) + if got != str { + t.Errorf("json.Marshal() = %v; want %v", got, str) + } + + wantV := T{F: easyjson.RawMessage([]byte(`"test"`)), Fnil: easyjson.RawMessage([]byte("null"))} + var gotV T + + err = json.Unmarshal([]byte(str), &gotV) + if err != nil { + t.Errorf("json.Unmarshal() error: %v", err) + } + if !reflect.DeepEqual(gotV, wantV) { + t.Errorf("json.Unmarshal() = %v; want %v", gotV, wantV) + } +}