Standard marshallers for easyjson.RawMessage.

This commit is contained in:
Victor Starodub
2016-03-29 16:04:34 +03:00
parent 4fd343250a
commit 9a3d2c62e3
2 changed files with 47 additions and 0 deletions
+16
View File
@@ -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
+31
View File
@@ -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)
}
}