francoispqt / gojay

high performance JSON encoder/decoder with stream API for Golang
MIT License
2.11k stars 112 forks source link

codegen: Trick fields #43

Closed freman closed 5 years ago

freman commented 6 years ago

Hi.

Might be a tiny tiny use case, but it'd be awesome to be able to pass say gojay:"fieldname|altfieldname" and have gojay generate code around using whichever field it finds

The actual fields I'm looking at are 'ip_prefix' and 'ipv6_prefix' they parse the same as far as I'm concerned.

Perhaps some way to make the code gen extensible?

Perhaps some inspiration can be drawn from https://github.com/clipperhouse/gen?

chasebrewsky commented 5 years ago

Wouldn't this enhancement go against the reason for this library? From what I understand from the description of this library, it was created for the purpose of avoiding code generation altogether since it ends up being unreadable and adds extra moving parts you have to stitch together to create the final binary.

If you want to use one or the other field when decoding an IP address from a JSON object you just create a function that adheres to the decoder interface that looks like this:

func (o *Object) UnmarshalJSONObject(dec *Decoder, key string) error {
    switch key {
    case "ip_prefix":
        dec.String(&o.ip)
    case "ipv6_prefix":
        dec.String(&o.ip)
    }
    return nil
}

This maps those two keys to output into the same field. If you have both of those fields showing up in your JSON, then you probably need a new structure that includes those two fields separately or have some form of validation on the structure itself to prevent that from happening.

francoispqt commented 5 years ago

I'm closing that as it won't be done in the near future in the generator. You can implement it if you want and submit a PR.