mirror of
https://github.com/netbirdio/easyjson.git
synced 2026-05-22 18:44:42 -07:00
Standard marshallers for easyjson.RawMessage.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user