Last active
June 28, 2022 12:00
-
-
Save js2854/b1a07ff8808221b579bbec7b60232dfd to your computer and use it in GitHub Desktop.
jsoniter ignore omitempty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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