Skip to content

Instantly share code, notes, and snippets.

@js2854
Last active June 28, 2022 12:00
Show Gist options
  • Save js2854/b1a07ff8808221b579bbec7b60232dfd to your computer and use it in GitHub Desktop.
Save js2854/b1a07ff8808221b579bbec7b60232dfd to your computer and use it in GitHub Desktop.
jsoniter ignore omitempty
import jsoniter "github.com/json-iterator/go"
type NotOmitemptyValEncoder struct {
encoder jsoniter.ValEncoder
}
func (codec *NotOmitemptyValEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
codec.encoder.Encode(ptr, stream)
}
func (codec *NotOmitemptyValEncoder) IsEmpty(ptr unsafe.Pointer) bool {
return false
}
// NotOmitemptyExtension 忽略omitempty的扩展
// func init中注册 jsoniter.RegisterExtension(new(NotOmitemptyExtension)) 即可
type NotOmitemptyExtension struct {
jsoniter.DummyExtension
}
func (ed NotOmitemptyExtension) DecorateEncoder(typ reflect2.Type, encoder jsoniter.ValEncoder) jsoniter.ValEncoder {
return &NotOmitemptyValEncoder{encoder: encoder}
}
// func TestJsonMarshaler(t *testing.T) {
// type before struct {
// Name string `json:"name,omitempty"`
// Age int `json:"age,omitempty"`
// }
// type after struct {
// Name string `json:"name,omitempty"`
// Age int `json:"age,omitempty"`
// }
// data1, _ := jsoniter.Marshal(&before{})
// assert.Equal(t, `{}`, string(data1))
// jsoniter.RegisterExtension(new(NotOmitemptyExtension))
// data2, _ := jsoniter.Marshal(&after{})
// assert.Equal(t, `{"name":"","age":0}`, string(data2))
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment