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. 21
      encoding/json/json.go

@ -31,13 +31,23 @@ func init() {
type codec struct{}
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)
default:
return json.Marshal(m)
}
return json.Marshal(v)
}
func (codec) Unmarshal(data []byte, v interface{}) error {
switch m := v.(type) {
case json.Unmarshaler:
return m.UnmarshalJSON(data)
case proto.Message:
return UnmarshalOptions.Unmarshal(data, m)
default:
rv := reflect.ValueOf(v)
for rv := rv; rv.Kind() == reflect.Ptr; {
if rv.IsNil() {
@ -45,12 +55,11 @@ func (codec) Unmarshal(data []byte, v interface{}) error {
}
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 {
if m, ok := reflect.Indirect(rv).Interface().(proto.Message); ok {
return UnmarshalOptions.Unmarshal(data, m)
}
return json.Unmarshal(data, v)
return json.Unmarshal(data, m)
}
}
func (codec) Name() string {

Loading…
Cancel
Save