Add encoder options to serialize 'nil' maps/slices as empty object/array.

This commit is contained in:
Victor Starodub
2016-11-03 17:18:12 +03:00
parent a620b7294c
commit 159cdb893c
4 changed files with 50 additions and 2 deletions
+2 -2
View File
@@ -121,7 +121,7 @@ func (g *Generator) genTypeEncoderNoCheck(t reflect.Type, in string, tags fieldT
if t.Elem().Kind() == reflect.Uint8 {
fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+")")
} else {
fmt.Fprintln(g.out, ws+"if "+in+" == nil {")
fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilSliceAsEmpty) == 0 {")
fmt.Fprintln(g.out, ws+` out.RawString("null")`)
fmt.Fprintln(g.out, ws+"} else {")
fmt.Fprintln(g.out, ws+" out.RawByte('[')")
@@ -178,7 +178,7 @@ func (g *Generator) genTypeEncoderNoCheck(t reflect.Type, in string, tags fieldT
}
tmpVar := g.uniqueVarName()
fmt.Fprintln(g.out, ws+"if "+in+" == nil {")
fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 {")
fmt.Fprintln(g.out, ws+" out.RawString(`null`)")
fmt.Fprintln(g.out, ws+"} else {")
fmt.Fprintln(g.out, ws+" out.RawByte('{')")
+11
View File
@@ -10,8 +10,19 @@ import (
"github.com/mailru/easyjson/buffer"
)
// Flags describe various encoding options. The behavior may be actually implemented in the encoder, but
// Flags field in Writer is used to set and pass them around.
type Flags int
const (
NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'.
NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'.
)
// Writer is a JSON writer.
type Writer struct {
Flags Flags
Error error
Buffer buffer.Buffer
}
+27
View File
@@ -156,3 +156,30 @@ func TestUnderflowArray(t *testing.T) {
t.Errorf("Unmarshal(%v) = %+v; want %+v", arrayUnderflowString, a, arrayUnderflowValue)
}
}
func TestEncodingFlags(t *testing.T) {
for i, test := range []struct {
Flags jwriter.Flags
In easyjson.Marshaler
Want string
}{
{0, EncodingFlagsTestMap{}, `{"F":null}`},
{0, EncodingFlagsTestSlice{}, `{"F":null}`},
{jwriter.NilMapAsEmpty, EncodingFlagsTestMap{}, `{"F":{}}`},
{jwriter.NilSliceAsEmpty, EncodingFlagsTestSlice{}, `{"F":[]}`},
} {
w := &jwriter.Writer{Flags: test.Flags}
test.In.MarshalEasyJSON(w)
data, err := w.BuildBytes()
if err != nil {
t.Errorf("[%v] easyjson.Marshal(%+v) error: %v", i, test.In, err)
}
v := string(data)
if v != test.Want {
t.Errorf("[%v] easyjson.Marshal(%+v) = %v; want %v", i, test.In, v, test.Want)
}
}
}
+10
View File
@@ -624,3 +624,13 @@ type RequiredOptionalStruct struct {
FirstName string `json:"first_name,required"`
Lastname string `json:"last_name"`
}
//easyjson:json
type EncodingFlagsTestMap struct {
F map[string]string
}
//easyjson:json
type EncodingFlagsTestSlice struct {
F []string
}