diff --git a/encode.go b/encode.go index d258c45..0874e84 100644 --- a/encode.go +++ b/encode.go @@ -112,7 +112,7 @@ func (e *Encoder) EncodeWithOption(v interface{}, opts ...EncodeOption) error { } } header := (*interfaceHeader)(unsafe.Pointer(&v)) - buf, err := e.encode(header) + buf, err := e.encode(header, v == nil) if err != nil { return err } @@ -160,8 +160,8 @@ func (e *Encoder) reset() { e.unorderedMap = false } -func (e *Encoder) encodeForMarshal(header *interfaceHeader) ([]byte, error) { - buf, err := e.encode(header) +func (e *Encoder) encodeForMarshal(header *interfaceHeader, isNil bool) ([]byte, error) { + buf, err := e.encode(header, isNil) if err != nil { return nil, err } @@ -178,9 +178,9 @@ func (e *Encoder) encodeForMarshal(header *interfaceHeader) ([]byte, error) { return copied, nil } -func (e *Encoder) encode(header *interfaceHeader) ([]byte, error) { +func (e *Encoder) encode(header *interfaceHeader, isNil bool) ([]byte, error) { b := e.buf[:0] - if header.ptr == nil { + if isNil { b = encodeNull(b) if e.enabledIndent { b = encodeIndentComma(b) diff --git a/json.go b/json.go index 28c6094..4f02347 100644 --- a/json.go +++ b/json.go @@ -163,7 +163,7 @@ func MarshalNoEscape(v interface{}) ([]byte, error) { var b *bytes.Buffer enc := NewEncoder(b) header := (*interfaceHeader)(unsafe.Pointer(&v)) - bytes, err := enc.encodeForMarshal(header) + bytes, err := enc.encodeForMarshal(header, v == nil) if err != nil { enc.release() return nil, err @@ -183,7 +183,7 @@ func MarshalWithOption(v interface{}, opts ...EncodeOption) ([]byte, error) { } header := (*interfaceHeader)(unsafe.Pointer(&v)) enc.ptr = header.ptr - bytes, err := enc.encodeForMarshal(header) + bytes, err := enc.encodeForMarshal(header, v == nil) if err != nil { enc.release() return nil, err @@ -211,7 +211,7 @@ func MarshalIndentWithOption(v interface{}, prefix, indent string, opts ...Encod enc.SetIndent(prefix, indent) header := (*interfaceHeader)(unsafe.Pointer(&v)) enc.ptr = header.ptr - bytes, err := enc.encodeForMarshal(header) + bytes, err := enc.encodeForMarshal(header, v == nil) if err != nil { enc.release() return nil, err @@ -414,7 +414,7 @@ func HTMLEscape(dst *bytes.Buffer, src []byte) { enc.SetEscapeHTML(true) header := (*interfaceHeader)(unsafe.Pointer(&v)) enc.ptr = header.ptr - enc.buf, _ = enc.encode(header) + enc.buf, _ = enc.encode(header, v == nil) dst.Write(enc.buf[:len(enc.buf)-1]) // remove last ',' character }