Encoding

    • form
    • json
    • protobuf
    • xml
    • yaml
    1. // https://github.com/go-kratos/kratos/blob/main/encoding/json/json.go
    2. package json
    3. import (
    4. "encoding/json"
    5. "reflect"
    6. "github.com/go-kratos/kratos/v2/encoding"
    7. "google.golang.org/protobuf/encoding/protojson"
    8. "google.golang.org/protobuf/proto"
    9. )
    10. // Name is the name registered for the json codec.
    11. const Name = "json"
    12. var (
    13. // MarshalOptions is a configurable JSON format marshaller.
    14. MarshalOptions = protojson.MarshalOptions{
    15. }
    16. // UnmarshalOptions is a configurable JSON format parser.
    17. UnmarshalOptions = protojson.UnmarshalOptions{
    18. DiscardUnknown: true,
    19. }
    20. func init() {
    21. encoding.RegisterCodec(codec{})
    22. }
    23. // codec is a Codec implementation with json.
    24. type codec struct{}
    25. func (codec) Marshal(v interface{}) ([]byte, error) {
    26. switch m := v.(type) {
    27. case json.Marshaler:
    28. return m.MarshalJSON()
    29. case proto.Message:
    30. return MarshalOptions.Marshal(m)
    31. default:
    32. return json.Marshal(m)
    33. }
    34. }
    35. func (codec) Unmarshal(data []byte, v interface{}) error {
    36. switch m := v.(type) {
    37. case json.Unmarshaler:
    38. return m.UnmarshalJSON(data)
    39. case proto.Message:
    40. default:
    41. for rv := rv; rv.Kind() == reflect.Ptr; {
    42. if rv.IsNil() {
    43. rv.Set(reflect.New(rv.Type().Elem()))
    44. }
    45. rv = rv.Elem()
    46. }
    47. if m, ok := reflect.Indirect(rv).Interface().(proto.Message); ok {
    48. return UnmarshalOptions.Unmarshal(data, m)
    49. }
    50. return json.Unmarshal(data, m)
    51. }
    52. }
    53. func (codec) Name() string {
    54. return Name
    55. }

    Register Custom Codec

    Get the Codec

    1. jsonCodec := encoding.GetCodec("json")

    Serialization

    Deserialization

    1. // You should manually import this package if you use it directly:import _ "github.com/go-kratos/kratos/v2/encoding/json"
    2. jsonCodec := encoding.GetCodec("json")
    3. type user struct {
    4. Name string
    5. Age string
    6. state bool
    7. }
    8. u := &user{}
    9. jsonCodec.Unmarshal([]byte(`{"Name":"kratos","Age":"2"}`), &u)
    10. //output &{kratos 2 false}