Skip to content

Commit

Permalink
feat: add option on sonic.Config
Browse files Browse the repository at this point in the history
  • Loading branch information
AsterDY committed Jul 8, 2022
1 parent 6d29395 commit 840d7ac
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
UseUnicodeErrors bool
DisallowUnknownFields bool
CopyString bool
NoNullSliceOrMap bool
}

var (
Expand Down
18 changes: 17 additions & 1 deletion encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@
package sonic

import (
`os`
`bytes`
`encoding`
`encoding/json`
`fmt`
`log`
`math`
`os`
`reflect`
`regexp`
`runtime`
Expand All @@ -36,6 +36,7 @@ import (
`unsafe`

`github.com/bytedance/sonic/encoder`
`github.com/stretchr/testify/assert`
)

var (
Expand Down Expand Up @@ -1153,3 +1154,18 @@ func TestMarshalerError(t *testing.T) {
}
}
}

func TestMarshalNullNil(t *testing.T) {
var v = struct {
A []int
B map[string]int
}{}
o, e := Marshal(v)
assert.Nil(t, e)
assert.Equal(t, `{"A":null,"B":null}`, string(o))
o, e = Config{
NoNullSliceOrMap: true,
}.Froze().Marshal(v)
assert.Nil(t, e)
assert.Equal(t, `{"A":[],"B":{}}`, string(o))
}
1 change: 1 addition & 0 deletions encoder/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const (
// instead of 'null'
NoNullSliceOrMap Options = 1 << bitNoNullSliceOrMap

// CompatibleWithStd is used to be compatible with std encoder.
CompatibleWithStd Options = SortMapKeys | EscapeHTML | CompactMarshaler
)

Expand Down
3 changes: 3 additions & 0 deletions sonic.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ func (cfg Config) Froze() API {
if cfg.CopyString {
api.decoderOpts |= decoder.OptionCopyString
}
if cfg.NoNullSliceOrMap {
api.encoderOpts |= encoder.NoNullSliceOrMap
}
return api
}

Expand Down

0 comments on commit 840d7ac

Please sign in to comment.