You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/encoding/json/json.go

58 lines
1.2 KiB

4 years ago
package json
import (
"encoding/json"
"reflect"
4 years ago
"github.com/go-kratos/kratos/v2/encoding"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
4 years ago
)
// Name is the name registered for the json codec.
const Name = "json"
var (
// MarshalOptions is a configurable JSON format marshaler.
MarshalOptions = protojson.MarshalOptions{
EmitUnpopulated: true,
}
// UnmarshalOptions is a configurable JSON format parser.
UnmarshalOptions = protojson.UnmarshalOptions{
DiscardUnknown: true,
}
)
4 years ago
func init() {
encoding.RegisterCodec(codec{})
}
// codec is a Codec implementation with json.
type codec struct{}
func (codec) Marshal(v interface{}) ([]byte, error) {
if m, ok := v.(proto.Message); ok {
return MarshalOptions.Marshal(m)
}
4 years ago
return json.Marshal(v)
}
func (codec) Unmarshal(data []byte, v interface{}) error {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Ptr {
if rv.IsNil() {
rv.Set(reflect.New(rv.Type().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)
}
4 years ago
return json.Unmarshal(data, v)
}
func (codec) Name() string {
return Name
}