Skip to content

added flag for marshalling nil slices to [] instead of null #533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type Config struct {
ValidateJsonRawMessage bool
ObjectFieldMustBeSimpleString bool
CaseSensitive bool
NilSafeCollection bool // marshalling nil slices/maps to []/{} instead of null
}

// API the public interface of this package.
Expand Down Expand Up @@ -80,6 +81,7 @@ type frozenConfig struct {
streamPool *sync.Pool
iteratorPool *sync.Pool
caseSensitive bool
nilSafeCollection bool
}

func (cfg *frozenConfig) initCache() {
Expand Down Expand Up @@ -134,6 +136,7 @@ func (cfg Config) Froze() API {
onlyTaggedField: cfg.OnlyTaggedField,
disallowUnknownFields: cfg.DisallowUnknownFields,
caseSensitive: cfg.CaseSensitive,
nilSafeCollection: cfg.NilSafeCollection,
}
api.streamPool = &sync.Pool{
New: func() interface{} {
Expand Down
39 changes: 39 additions & 0 deletions misc_tests/jsoniter_nil_safe_collection_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package misc_tests

import (
"testing"

jsoniter "github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)

func Test_marshal_nil_safe_collection(t *testing.T) {
type B struct {
Arr []string
Arr2 []string
Map map[string]string
}

type A struct {
Arr []string
Arr2 []string
Map map[string]string
Struct B
StructPoint *B
StructSlice []B
StructSlicePoint []*B
StructMap map[string]B
StructMapPoint map[string]*B
}

a := A{}
a.Arr2 = append(a.Arr2, "aa")
should := require.New(t)
out := `{"Arr":[],"Arr2":["aa"],"Map":{},"Struct":{"Arr":[],"Arr2":[],"Map":{}},"StructPoint":null,"StructSlice":[],"StructSlicePoint":[],"StructMap":{},"StructMapPoint":{}}`
aout, err := jsoniter.Config{NilSafeCollection: true, SortMapKeys: true}.Froze().Marshal(&a)
should.Nil(err)
should.Equal(out, string(aout))
bout, err := jsoniter.Config{NilSafeCollection: true, SortMapKeys: false}.Froze().Marshal(&a)
should.Nil(err)
should.Equal(out, string(bout))
}
36 changes: 24 additions & 12 deletions reflect_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,17 @@ func encoderOfMap(ctx *ctx, typ reflect2.Type) ValEncoder {
mapType := typ.(*reflect2.UnsafeMapType)
if ctx.sortMapKeys {
return &sortKeysMapEncoder{
mapType: mapType,
keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()),
elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()),
mapType: mapType,
keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()),
elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()),
nilSafeCollection: ctx.nilSafeCollection,
}
}
return &mapEncoder{
mapType: mapType,
keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()),
elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()),
mapType: mapType,
keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()),
elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()),
nilSafeCollection: ctx.nilSafeCollection,
}
}

Expand Down Expand Up @@ -243,13 +245,18 @@ func (encoder *dynamicMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool {
}

type mapEncoder struct {
mapType *reflect2.UnsafeMapType
keyEncoder ValEncoder
elemEncoder ValEncoder
mapType *reflect2.UnsafeMapType
keyEncoder ValEncoder
elemEncoder ValEncoder
nilSafeCollection bool
}

func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
if *(*unsafe.Pointer)(ptr) == nil {
if encoder.nilSafeCollection {
stream.WriteEmptyObject()
return
}
stream.WriteNil()
return
}
Expand Down Expand Up @@ -277,13 +284,18 @@ func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool {
}

type sortKeysMapEncoder struct {
mapType *reflect2.UnsafeMapType
keyEncoder ValEncoder
elemEncoder ValEncoder
mapType *reflect2.UnsafeMapType
keyEncoder ValEncoder
elemEncoder ValEncoder
nilSafeCollection bool
}

func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
if *(*unsafe.Pointer)(ptr) == nil {
if encoder.nilSafeCollection {
stream.WriteEmptyObject()
return
}
stream.WriteNil()
return
}
Expand Down
11 changes: 8 additions & 3 deletions reflect_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,21 @@ func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder {
func encoderOfSlice(ctx *ctx, typ reflect2.Type) ValEncoder {
sliceType := typ.(*reflect2.UnsafeSliceType)
encoder := encoderOfType(ctx.append("[sliceElem]"), sliceType.Elem())
return &sliceEncoder{sliceType, encoder}
return &sliceEncoder{sliceType, encoder, ctx.nilSafeCollection}
}

type sliceEncoder struct {
sliceType *reflect2.UnsafeSliceType
elemEncoder ValEncoder
sliceType *reflect2.UnsafeSliceType
elemEncoder ValEncoder
nilSafeCollection bool
}

func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
if encoder.sliceType.UnsafeIsNil(ptr) {
if encoder.nilSafeCollection {
stream.WriteEmptyArray()
return
}
stream.WriteNil()
return
}
Expand Down