json-iterator / go

A high-performance 100% compatible drop-in replacement of "encoding/json"
http://jsoniter.com/migrate-from-go-std.html
MIT License
13.43k stars 1.03k forks source link

DecorateEncoder to omitempty results in empty values instead #579

Open alonbg opened 3 years ago

alonbg commented 3 years ago

Trying to get an omitempty behavior for all fields of a bunch of third party well nested structs. getting empty values instead.

type omitemptyExtension struct {
    jsoniter.DummyExtension
}

type omitemptyEncoder struct {
    encoder jsoniter.ValEncoder
}

func (o *omitemptyEncoder) IsEmpty(ptr unsafe.Pointer) bool {
    return o.encoder.IsEmpty(ptr)
}

func (o *omitemptyEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
    if o.IsEmpty(ptr) {
        return
    }
    o.encoder.Encode(ptr, stream)
}

func (ext *omitemptyExtension) DecorateEncoder(typ reflect2.Type, encoder jsoniter.ValEncoder) jsoniter.ValEncoder {
    return &omitemptyEncoder{
        encoder: encoder,
    }
}

If binding.Encoder.(*structFieldEncoder).omitempty was changeable, I assume then, it could have been modified via UpdateStructDescriptor(structDescriptor *StructDescriptor) (i.e. binding.Encoder.(*structFieldEncoder).OmitEmpty(true) )