preserve nil maps and slices in generated Marshal* methods

master
Felix Lange 8 years ago
parent 9f20d19e75
commit 72fbea27b0
  1. 10
      genmethod.go
  2. 8
      internal/tests/mapconv/output.go
  3. 8
      internal/tests/sliceconv/output.go

@ -206,7 +206,15 @@ func (m *marshalMethod) marshalConversions(from, to Var, format string) (s []Sta
for _, f := range m.mtyp.Fields {
accessFrom := Dotted{Receiver: from, Name: f.name}
accessTo := Dotted{Receiver: to, Name: f.name}
s = append(s, m.convert(accessFrom, accessTo, f.origTyp, f.typ)...)
conversion := m.convert(accessFrom, accessTo, f.origTyp, f.typ)
if underlyingMap(f.origTyp) != nil || underlyingSlice(f.origTyp) != nil {
// Preserve nil maps and slices.
conversion = []Statement{If{
Condition: NotEqual{Lhs: accessFrom, Rhs: NIL},
Body: conversion,
}}
}
s = append(s, conversion...)
}
return s
}

@ -13,14 +13,18 @@ func (x *X) MarshalJSON() ([]byte, error) {
Named namedMap2
}
var enc XJSON
if x.Map != nil {
enc.Map = make(map[replacedString]replacedInt, len(x.Map))
for k, v := range x.Map {
enc.Map[replacedString(k)] = replacedInt(v)
}
}
if x.Named != nil {
enc.Named = make(namedMap2, len(x.Named))
for k, v := range x.Named {
enc.Named[replacedString(k)] = replacedInt(v)
}
}
return json.Marshal(&enc)
}
@ -58,14 +62,18 @@ func (x *X) MarshalYAML() (interface{}, error) {
Named namedMap2
}
var enc XYAML
if x.Map != nil {
enc.Map = make(map[replacedString]replacedInt, len(x.Map))
for k, v := range x.Map {
enc.Map[replacedString(k)] = replacedInt(v)
}
}
if x.Named != nil {
enc.Named = make(namedMap2, len(x.Named))
for k, v := range x.Named {
enc.Named[replacedString(k)] = replacedInt(v)
}
}
return &enc, nil
}

@ -13,14 +13,18 @@ func (x *X) MarshalJSON() ([]byte, error) {
Named namedSlice2
}
var enc XJSON
if x.Slice != nil {
enc.Slice = make([]replacedInt, len(x.Slice))
for k, v := range x.Slice {
enc.Slice[k] = replacedInt(v)
}
}
if x.Named != nil {
enc.Named = make(namedSlice2, len(x.Named))
for k, v := range x.Named {
enc.Named[k] = replacedInt(v)
}
}
return json.Marshal(&enc)
}
@ -58,14 +62,18 @@ func (x *X) MarshalYAML() (interface{}, error) {
Named namedSlice2
}
var enc XYAML
if x.Slice != nil {
enc.Slice = make([]replacedInt, len(x.Slice))
for k, v := range x.Slice {
enc.Slice[k] = replacedInt(v)
}
}
if x.Named != nil {
enc.Named = make(namedSlice2, len(x.Named))
for k, v := range x.Named {
enc.Named[k] = replacedInt(v)
}
}
return &enc, nil
}

Loading…
Cancel
Save