refactor(encoding): optimize json encoding (#1339)

* fix(encoding): optimize json encoding, add support for other encoding implementation such as easyjson etc.

Co-authored-by: corel <corelchen@qq.com>
pull/1360/head
aiscrm 3 years ago committed by GitHub
parent dee204efc2
commit 0b09fcd76d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 35
      encoding/json/json.go

@ -31,26 +31,35 @@ func init() {
type codec struct{} type codec struct{}
func (codec) Marshal(v interface{}) ([]byte, error) { func (codec) Marshal(v interface{}) ([]byte, error) {
if m, ok := v.(proto.Message); ok { switch m := v.(type) {
case json.Marshaler:
return m.MarshalJSON()
case proto.Message:
return MarshalOptions.Marshal(m) return MarshalOptions.Marshal(m)
default:
return json.Marshal(m)
} }
return json.Marshal(v)
} }
func (codec) Unmarshal(data []byte, v interface{}) error { func (codec) Unmarshal(data []byte, v interface{}) error {
rv := reflect.ValueOf(v) switch m := v.(type) {
for rv := rv; rv.Kind() == reflect.Ptr; { case json.Unmarshaler:
if rv.IsNil() { return m.UnmarshalJSON(data)
rv.Set(reflect.New(rv.Type().Elem())) case proto.Message:
}
rv = rv.Elem()
}
if m, ok := v.(proto.Message); ok {
return UnmarshalOptions.Unmarshal(data, m)
} else if m, ok := reflect.Indirect(rv).Interface().(proto.Message); ok {
return UnmarshalOptions.Unmarshal(data, m) return UnmarshalOptions.Unmarshal(data, m)
default:
rv := reflect.ValueOf(v)
for rv := rv; rv.Kind() == reflect.Ptr; {
if rv.IsNil() {
rv.Set(reflect.New(rv.Type().Elem()))
}
rv = rv.Elem()
}
if m, ok := reflect.Indirect(rv).Interface().(proto.Message); ok {
return UnmarshalOptions.Unmarshal(data, m)
}
return json.Unmarshal(data, m)
} }
return json.Unmarshal(data, v)
} }
func (codec) Name() string { func (codec) Name() string {

Loading…
Cancel
Save