github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/codec/json.go (about)

     1  package codec
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  
     7  	"github.com/hzmsrv/sonic"
     8  	"github.com/hzmsrv/sonic/decoder"
     9  )
    10  
    11  // jsonCodec uses json marshaler and unmarshaler.
    12  type jsonCodec struct{}
    13  
    14  var JSON SerializeType = RegisterCodec("Json", new(jsonCodec))
    15  var _ SerializeType = RegisterCodec("application/json", new(jsonCodec))
    16  
    17  func (c jsonCodec) String() string {
    18  	return "Json"
    19  }
    20  
    21  // Encode encodes an object into slice of bytes.
    22  func (c jsonCodec) Encode(i interface{}) ([]byte, error) {
    23  	return sonic.Marshal(i)
    24  	//return json.Marshal(i)
    25  	//return bson.Marshal(i)
    26  }
    27  
    28  // Decode decodes an object from slice of bytes.
    29  func (c jsonCodec) Decode(data []byte, i interface{}) error {
    30  	// FIXME TODO 时间转换错误
    31  	dc := decoder.NewStreamDecoder(bytes.NewReader(data))
    32  	dc.UseInt64()
    33  	//dc.UseNumber()
    34  	return dc.Decode(&i)
    35  }
    36  
    37  func (c jsonCodec) __Decode(data []byte, i interface{}) error {
    38  	dc := json.NewDecoder(bytes.NewBuffer(data))
    39  	dc.UseNumber()
    40  	return dc.Decode(&i)
    41  }