序列化
// https://github.com/go-kratos/kratos/blob/main/encoding/json/json.go
package json
import (
"encoding/json"
"reflect"
"github.com/go-kratos/kratos/v2/encoding"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
// Name is the name registered for the json codec.
const Name = "json"
var (
// MarshalOptions is a configurable JSON format marshaller.
MarshalOptions = protojson.MarshalOptions{
}
// UnmarshalOptions is a configurable JSON format parser.
UnmarshalOptions = protojson.UnmarshalOptions{
}
)
func init() {
encoding.RegisterCodec(codec{})
}
// codec is a Codec implementation with json.
type codec struct{}
func (codec) Marshal(v interface{}) ([]byte, error) {
switch m := v.(type) {
case json.Marshaler:
return m.MarshalJSON()
case proto.Message:
return MarshalOptions.Marshal(m)
default:
return json.Marshal(m)
}
}
func (codec) Unmarshal(data []byte, v interface{}) error {
switch m := v.(type) {
case json.Unmarshaler:
return m.UnmarshalJSON(data)
case proto.Message:
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)
}
}
func (codec) Name() string {
return Name
}
注册 Codec
获取 Codec
jsonCodec := encoding.GetCodec("json")
序列化
反序列化
// 直接使用内置 Codec 时需要 import _ "github.com/go-kratos/kratos/v2/encoding/json"
jsonCodec := encoding.GetCodec("json")
type user struct {
Name string
Age string
state bool
}
u := &user{}
jsonCodec.Unmarshal([]byte(`{"Name":"kratos","Age":"2"}`), &u)
// 输出:&{kratos 2 false}